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.