Suppose 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 that the page does not refresh. You can do this in at least two ways:
1. Attaching an event handler to the actual representation of the form:
$("#settings-form").submit(function(event){
event.preventDefault();
var data = $(this).serialize();
});
Here I would add type='submit'to the button submit-btn.
2. Attaching the event handler to the button:
$("#submit-btn").click(function(){
var data = $("#settings-form").serialize();
});
And here it submit-btngetstype='button'
My question is: which option is better and why? It's not about which attribute value is typebetter for buttonin this case, but why the event handler 1 is better than 2 or vice versa.