How to get the form parent of an input?

2019-01-04 01:25发布

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"));

10条回答
劳资没心,怎么记你
2楼-- · 2019-01-04 01:46

Native DOM elements that are inputs also have a form attribute that points to the form they belong to:

var form = element.form;
alert($(form).attr('name'));

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 with closest:

var $form = $(element).closest('form');
alert($form.attr('name'));

Also, see this MDN link on the form property of HTMLInputElement:

查看更多
看我几分像从前
3楼-- · 2019-01-04 01:49

Using jQuery:

function doSomething(element) {
    var form = $(element).closest("form").get().
    //do something with the form.
}
查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-04 01:49

If using jQuery and have a handle to any form element, you need to get(0) the element before using .form

var my_form = $('input[name=first_name]').get(0).form;
查看更多
Ridiculous、
5楼-- · 2019-01-04 01:52

would this work? (leaving action blank submits form back to itself too, right?)

<form action="">
<select name="memberid" onchange="this.form.submit();">
<option value="1">member 1</option>
<option value="2">member 2</option>
</select>

"this" would be the select element, .form would be its parent form. Right?

查看更多
登录 后发表回答