Is there an easy way in jQuery to return the owner form for a deeply-nested checkbox (or input) element? Here's an example of what I mean:
<form>
<table>
<thead>
<tr>
<td>123</td>
</tr>
</thead>
<tfoot>
<tr>
<td><input type="checkbox" class="checkall" /></td>
</tr>
</tfoot>
</table>
</form>
Then I have the following jQuery code:
$('checkbox.checkall').each(function() {
// Access form element of the checkbox here
});
In the above example, I would like to obtain the form to which the checkbox belongs. Natually, I could do this using a chained parent()
method, but the checkbox might not always be the same nesting depth from the root form element.
Sorry if it's not clear, but it's difficult to explain.
Is there an easy way in jQuery to return the owner form for a deeply-nested checkbox (or input) element? Here's an example of what I mean:
<form>
<table>
<thead>
<tr>
<td>123</td>
</tr>
</thead>
<tfoot>
<tr>
<td><input type="checkbox" class="checkall" /></td>
</tr>
</tfoot>
</table>
</form>
Then I have the following jQuery code:
$('checkbox.checkall').each(function() {
// Access form element of the checkbox here
});
In the above example, I would like to obtain the form to which the checkbox belongs. Natually, I could do this using a chained parent()
method, but the checkbox might not always be the same nesting depth from the root form element.
Sorry if it's not clear, but it's difficult to explain.
Share Improve this question asked Mar 23, 2011 at 13:36 BenMBenM 53.2k26 gold badges115 silver badges172 bronze badges5 Answers
Reset to default 5Get the closest form
$("input[type=checkbox]").closest("form");
From jQuery API:
Description: Get the first ancestor element that matches the selector, beginning at the current element and progressing up through the DOM tree.
.closest( selector )
selector: A string containing a selector expression to match elements against.
Form fields have a form
property which returns the FORM element that contains them.
$('checkbox.checkall').each(function() {
// Access form element of the checkbox here
var form = this.form;
});
Source: http://www.w3/TR/DOM-Level-2-HTML/html.html#ID-63239895
Live demo: http://jsfiddle/simevidas/9FPrX/1/
You could also use parents() thus:
$("input:checkbox").parents("form");
.closest()
sounds like the function you need.
It will return the closest parent of the element you gave to the function.
use parent()
$("input:checkbox").parent("form");
parents will give you all relevant parent(form) of this checkbox