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"));
This question is related to
javascript
jquery
forms
input
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.
Using jQuery:
function doSomething(element) {
var form = $(element).closest("form").get().
//do something with the form.
}
Every input has a form
property which points to the form the input belongs to, so simply:
function doSomething(element) {
var form = element.form;
}
simply as:
alert( $(this.form).attr('name') );
I needed to use element.attr('form')
instead of element.form
.
I use Firefox on Fedora 12.
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;
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
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
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?
This example of a Javascript function is called by an event listener to identify the form
function submitUpdate(event) {
trigger_field = document.getElementById(event.target.id);
trigger_form = trigger_field.form;
Source: Stackoverflow.com