Assume this simple HTML form:
<form id="settings-form">
<label>
Input data:
<input name="data"/>
</label>
<button id="submit-btn">Submit</button>
</form>
I want to submit this form using jQuery and AJAX, so the page will not be refreshed. You can do this in at least these two ways:
1. Attaching an event handler to the actual submission of the form:
$("#settings-form").submit(function(event){
event.preventDefault();
var data = $(this).serialize();
//Ajax code here
});
Here, I'd add type='submit'
to button submit-btn
.
2. Attaching an event handler to the button:
$("#submit-btn").click(function(){
var data = $("#settings-form").serialize(); // or this.closest("form").serialize()
//Ajax code here
});
And here, submit-btn
gets type='button'
My question is: Which option is better and why? This is not about which type
attribute value is better for the button
in this case, but why event handler 1 is better than 2 or vice-versa.
A form can be submitted by multiple sources, not only by clicking the submit button (eg: manually invoking $("form").submit()
or pressing Enter
).
Using the first option assures you of catching all possible submits on that form while the second option only blocks the submit when clicking the button. Its up to you to decide which one you need.
In terms of performance there is no difference.
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