Say I have the following HTML:
<form>
...some form fields...
<input type="submit" id="submitButton" value="Submit" />
</form>
And I have a javascript method validate
that checks the form fields for various invalid scenarios, returning true
if all is well or false
if there's something wrong.
Is there any real difference in jQuery between doing this:
$("form").submit(function() {
return validate();
});
...or doing this:
$("#submitButton").click(function(){
return validate();
});
And are there any advantages/disadvantages between the two?
Both <button type="submit"> and <input type="submit"> display as buttons and cause the form data to be submitted to the server. The difference is that <button> can have content, whereas <input> cannot (it is a null element).
A 'submit' input type has the default functionality of submitting the form it's placed in (though, of course, you can still add additional functionality using Javascript). A <button> with no type attribute inside a <form> will behave like <input type="submit"> . See the example here: sign-in-form.glitch.me.
submit() submits the entire form to a Servlet or anything where as $("#button1"). click() simply can be used to process anything like calling a function of javascript or even to submit the form.
The submit event fires when the user clicks a submit button ( <button> or <input type="submit">) or presses Enter while editing a field (e.g. <input type="text">) in a form. The event is not sent to the form when calling the form. submit() method directly.
The click callback is called only if the user actually click on the submit button. But there are cases in which you would submit the form automatically by javascript, in that case the click callback is not fired while the submit callback is. I would recommend to use always the submit for validation and intrinsic action of the form, while using the click callback for animation or other things related to the action of clicking on the button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With