HTML Topics
- HTML Intro
- HTML Basic
- HTML Editors
- HTML CSS
- HTML Tags
- HTML Deprecated Tags
- HTML Events
- HTML Event Attributes
- HTML Global Attributes
- HTML Attributes
- abbr
- accept
- accept-charset
- accesskey
- action
- align
- alt
- archive
- as
- async
- autocapitalize
- autocomplete
- autofocus
- autoplay
- axis
- bgcolor
- border
- cellpadding
- cellspacing
- char
- charoff
- charset
- checked
- cite
- class
- classid
- codebase
- codetype
- color
- cols
- colspan
- compact
- content
- contenteditable
- controls
- coords
- crossorigin
- data
- data-*
- datetime
- declare
- default
- defer
- dir
- dirname
- disabled
- download
- draggable
- enctype
- enterkeyhint
- for
- form
- formaction
- formenctype
- formmethod
- formnovalidate
- formtarget
- frame
- frameborder
- frameset
- headers
- height
- hidden
- high
- href
- hreflang
- hspace
- http-equiv
- id
- inert
- inputmode
- ismap
- kind
- label
- lang
- list
- loop
- low
- max
- maxlength
- media
- method
- min
- multiple
- muted
- name
- novalidate
- onabort
- onafterprint
- onbeforeprint
- onbeforeunload
- onblur
- oncanplay
- oncanplaythrough
- onchange
- onclick
- oncontextmenu
- oncopy
- oncuechange
- oncut
- ondblclick
- ondrag
- ondragend
- ondragenter
- ondragleave
- ondragover
- ondragstart
- ondrop
- ondurationchange
- onemptied
- onended
- onerror
- onfocus
- onhashchange
- oninput
- oninvalid
- onkeydown
- onkeypress
- onkeyup
- onload
- onloadeddata
- onloadedmetadata
- onloadstart
- onmousedown
- onmousemove
- onmouseout
- onmouseover
- onmouseup
- onmousewheel
- onoffline
- ononline
- onpagehide
- onpageshow
- onpaste
- onpause
- onplay
- onplaying
- onpopstate
- onprogress
- onratechange
- onreset
- onresize
- onscroll
- onsearch
- onseeked
- onseeking
- onselect
- onstalled
- onstorage
- onsubmit
- onsuspend
- ontimeupdate
- ontoggle
- onunload
- onvolumechange
- onwaiting
- onwheel
- open
- optimum
- pattern
- placeholder
- popover
- popovertarget
- popovertargetaction
- poster
- preload
- readonly
- rel
- required
- reversed
- rows
- rowspan
- sandbox
- scope
- selected
- shape
- size
- sizes
- span
- spellcheck
- src
- srcdoc
- srclang
- srcset
- start
- step
- style
- tabindex
- target
- title
- translate
- type
- usemap
- value
- width
- wrap
- HTML Comments
- HTML Entity
- HTML Head
- HTML Form
- HTML IndexedDB
- HTML Drag & Drop
- HTML Geolocation
- HTML Canvas
- HTML Status Code
- HTML Language Code
- HTML Country Code
- HTML Charset
- MIME Types
HTML onsubmit Attribute
Photo Credit to CodeToFun
🙋 Introduction
The onsubmit
attribute is a powerful feature in HTML that allows developers to define JavaScript code that will be executed when a form is submitted.
This attribute is applied to the <form> element and provides a way to perform actions or validations before the form data is sent to the server.
🎯 Purpose of onsubmit
The primary purpose of the onsubmit
attribute is to specify a JavaScript function that will be called when the form is submitted.
This function can be used to validate form data, perform calculations, or execute any custom logic before the form is processed.
💎 Values
The onsubmit
attribute accepts a JavaScript function as its value. This function will be triggered when the form is submitted.
It can be a predefined function or an inline function directly specified in the attribute.
📄 Example
Let's look at a simple example of how to use the onsubmit
attribute in an HTML form:
<form onsubmit="return validateForm()">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<input type="submit" value="Submit">
</form>
<script>
function validateForm() {
// Add your form validation logic here
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if (username === "" || password === "") {
alert("Please fill in all fields");
return false; // Prevent form submission
}
// Additional validation or processing can be added here
return true; // Allow form submission
}
</script>
🧠 How it Works
In this example, the onsubmit
attribute is set to call the validateForm function. This function checks if the username and password fields are filled, displaying an alert if they are not.
🔄 Dynamic Values with JavaScript
You can also dynamically set the onsubmit
attribute using JavaScript.
This is useful when you want to change the form submission behavior based on certain conditions or user interactions. Here's a brief example:
<script>
// Dynamically set onsubmit for a form
document.getElementById("dynamicForm").onsubmit = function() {
// Add your dynamic logic here
console.log("Form submitted dynamically");
return true; // Allow form submission
};
</script>
🧠 How it Works
In this script, the onsubmit
attribute is dynamically set for a form with the id dynamicForm. The function specified in the script will be called when the form is submitted.
🏆 Best Practices
- Use the
onsubmit
attribute for form validation and custom logic before submitting data to the server. - Ensure that the function specified in the
onsubmit
attribute returns true to allow form submission and false to prevent it. - Always test your forms with different browsers to ensure cross-browser compatibility.
🎉 Conclusion
The onsubmit
attribute in HTML provides a flexible way to execute JavaScript code before submitting a form.
By utilizing this attribute, you can enhance the user experience by validating data and performing custom actions seamlessly.
👨💻 Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (HTML onsubmit Attribute), please comment here. I will help you immediately.