Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the containing form of an input?

People also ask

How do I get input form?

Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc. Let's learn about the <input> tag, which helps you to take user input using the type attribute.

What is input element form?

<input>: The Input (Form Input) element. The <input> HTML element is used to create interactive controls for web-based forms in order to accept data from the user; a wide variety of types of input data and control widgets are available, depending on the device and user agent.


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:

  • https://developer.mozilla.org/en/DOM/HTMLInputElement#Properties

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

function doSomething(element) {
  var form = element.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


Using jQuery:

function doSomething(element) {
    var form = $(element).closest("form").get().
    //do something with the form.
}

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;