Suppose I've created the following handler (callback) for a form:
$('form').submit(function (event) {
event.preventDefault();
alert('form submitted');
});
Why does calling $('form').get(0).submit
not call the submit handler? The form just gets directly submitted.
.get(0)
returns the native js DOM element ( Same as $('form')[0]
) and then you are triggering the
submit event directly.
if you are trying to get the first Element use .eq(0)
and trigger the submit jQuery style using .submit()
.
Summary:
$('selector')[0]
~ returns the native js DOM element
.get(0)
~ Same as [0].
.eq(0)
~ returns the first element as a jQuery object .
More:
- Attach to submit event (jQuery):
$('form.selector').submit(function (e) { });
- Trigger Submit (jQuery):
$('form.selector').submit();
OR $('form.selector').trigger('submit');
- Trigger Submit on the first element:
$('form').eq(0).submit();
Demo: jsFiddle
I hope its what you need.
Demo jQuery:
$('form').submit(function (event) {
event.preventDefault(); // Will prevent the native handler from firing.
alert('form submitted :' + $(this).attr("id"));
});
//change the `.eq(index)` to 1 to trigger the submit on the second form:
$('form').eq(0).submit(); // Same as: $('form').eq(0).trigger("submit");
Demo HTML:
<form id="form1"></form>
<form id="form2"></form>