I need to get a reference to the FORM parent of an INPUT when I only have a reference to that INPUT. Is this possible with JavaScript? Use jQuery if you like.
function doSomething(element) {
//element is input object
//how to get reference to form?
}
This doesn't work:
var form = $(element).parents('form:first');
alert($(form).attr("name"));
Native DOM elements that are inputs also have a
form
attribute that points to the form they belong to:According to w3schools, the
.form
property of input fields is supported by IE 4.0+, Firefox 1.0+, Opera 9.0+, which is even more browsers that jQuery guarantees, so you should stick to this.If this were a different type of element (not an
<input>
), you could find the closest parent withclosest
:Also, see this MDN link on the
form
property ofHTMLInputElement
:Using jQuery:
If using jQuery and have a handle to any form element, you need to get(0) the element before using .form
would this work? (leaving action blank submits form back to itself too, right?)
"this" would be the select element, .form would be its parent form. Right?