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:31

simply as:

alert( $(this.form).attr('name') );
查看更多
Explosion°爆炸
3楼-- · 2019-01-04 01:32

Every input has a form property which points to the form the input belongs to, so simply:

function doSomething(element) {
  var form = element.form;
}
查看更多
一夜七次
4楼-- · 2019-01-04 01:32

I needed to use element.attr('form') instead of element.form

I use firefox on Fedora 12

查看更多
我命由我不由天
5楼-- · 2019-01-04 01:37

And one more....

var _e = $(e.target); // e being the event triggered
var element = _e.parent(); // the element the event was triggered on
console.log("_E " + element.context); // [object HTMLInputElement]
console.log("_E FORM " + element.context.form); // [object HTMLFormElement]
console.log("_E FORM " + element.context.form.id); // form id
查看更多
虎瘦雄心在
6楼-- · 2019-01-04 01:40

I use a bit of jQuery and old style javascript - less code

$($(this)[0].form) 

This is a complete reference to the form containing the element

查看更多
地球回转人心会变
7楼-- · 2019-01-04 01:42
function doSomething(element) {
  var form = element.form;
}

and in the html, you need to find that element, and add the attribut "form" to connect to that form, please refer to http://www.w3schools.com/tags/att_input_form.asp but this form attr doesn't support IE, for ie, you need to pass form id directly.

查看更多
登录 后发表回答