i have this html
<ul>
<li><form action="#" name="formName"></li>
<li><input type="text" name="someName" /></li>
<li><input type="text" name="someOtherName" /></li>
<li><input type="submit" name="submitButton" value="send"></li>
<li></form></li>
</ul>
How can i select the form that the input[name="submitButton"]
is part of ?
(when i click on the submit button i want to select the form and append some fields in it)
I would suggest using closest
, which selects the closest matching parent element:
$('input[name="submitButton"]').closest("form");
Instead of filtering by the name, I would do this:
$('input[type=submit]').closest("form");
You can use the form reference which exists on all inputs, this is much faster than .closest()
(5-10 times faster in Chrome and IE8). Works on IE6 & 7 too.
var input = $('input[type=submit]');
var form = input.length > 0 ? $(input[0].form) : $();
To me, this looks like the simplest/fastest:
$('form input[type=submit]').click(function() { // attach the listener to your button
var yourWantedObjectIsHere = $(this.form); // use the native JS object with `this`
});
see also jquery/js -- How do I select the parent form based on which submit button is clicked?
$('form#myform1').submit(function(e){
e.preventDefault(); //Prevent the normal submission action
var form = this;
// ... Handle form submission
});
As of HTML5 browsers one can use inputElement.form
- the value of the attribute must be an id of a <form>
element in the same document.
More info on MDN.
来源:https://stackoverflow.com/questions/1621714/jquery-find-parent-form