[javascript] get all the elements of a particular form

function getInputElements() {
    var inputs = document.getElementsByTagName("input");
}

The above code gets all the input elements on a page which has more than one form. How do I get the input elements of a particular form using plain JavaScript?

This question is related to javascript

The answer is


var inputs = document.getElementById("formId").getElementsByTagName("input");
var inputs = document.forms[1].getElementsByTagName("input");

Update for 2020:

var inputs = document.querySelectorAll("#formId input");

First, get all the elements

const getAllFormElements = element => Array.from(element.elements).filter(tag => ["select", "textarea", "input"].includes(tag.tagName.toLowerCase()));

Second, do something with them

const pageFormElements = getAllFormElements(document.body);
console.log(pageFormElements);

If you want to use a form, rather than the entire body of the page, you can do it like this

const pageFormElements = getAllFormElements(document.getElementById("my-form"));
console.log(formElements);

You're all concentrating on the word 'get' in the question. Try the 'elements' property of any form which is a collection that you can iterate through i.e. you write your own 'get' function.

Example:

function getFormElelemets(formName){
  var elements = document.forms[formName].elements;
  for (i=0; i<elements.length; i++){
    some code...
  }
}

Hope that helps.


If you have a reference to any field in the form or an event then you don't need to explicitly look up the form since every form field has a form attribute that points to its parent form. That means that once you have a filed reference to a DOM element userName then userName.form will be the form. If $userName is a jQuery object, then $userName.get(0).form will give you the form.

If you have an event then it will contain a target attribute which will point to the form field that triggered the event, which means you can access the form via myEvent.target.form.

Here is an example without any form lookup code.

<html>
<body>
    <form name="frm">
        <input type="text" name="login"><br/>
        <input type="password" name="password"><br/>
        <button type="submit" onclick="doLogin()">Login</button>
    </form>
    <script>
        function doLogin(e) {
            e = e || window.event;
            e.preventDefault();
            var form = e.target.form;
            alert("user:" + form.login.value + " password:" + form.password.value);
            e.target.form.submit();
        }
    </script>
</body>
</html>

If you have multiple forms on the page you still don't need to label them by name or id, because you'll always get the correct form instance via the event or via a reference to a field.


I could have sworn there used to be a convenient fields property on a form but … Must have been my imagination.

I just do this (for <form name="my_form"></form>) because I usually don't want fieldsets themselves:

let fields = Array.from(document.forms.my_form.querySelectorAll('input, select, textarea'));

Use this

var theForm = document.forms['formname']
[].slice.call(theForm).forEach(function (el, i) {
    console.log(el.value);
});

The el stands for the particular form element. It is better to use this than the foreach loop, as the foreach loop also returns a function as one of the element. However this only returns the DOM elements of the form.


How would you like to differentiate between forms? You can use different IDs, and then use this function:

function getInputElements(formId) {
    var form = document.getElementById(formId);
    if (form === null) {
        return null;
    }
    return form.getElementsByTagName('input');
}

You can use FormData if you want the values:

var form = document.getElementById('form-name');
var data = new FormData(form);
for (var [key, value] of data) {
    console.log(key, value)
}

let formFields     = form.querySelectorAll(`input:not([type='hidden']), select`)

ES6 version that has the advantage of ignoring the hidden fields if that is what you want


document.getElementById("someFormId").elements;

This collection will also contain <select>, <textarea> and <button> elements (among others), but you probably want that.


SIMPLE Form code

    <form id="myForm" name="myForm">
        <input type="text" name="User" value="Arsalan"/>
        <input type="password" name="pass" value="123"/>
        <input type="number" name="age" value="24"/>
        <input type="text" name="email" value="[email protected]"/>
        <textarea name="message">Enter Your Message Her</textarea>

    </form>

Javascript Code

//Assign Form by Id to a Variabe
    var myForm = document.getElementById("myForm");
    //Extract Each Element Value
    for (var i = 0; i < myForm.elements.length; i++) {
    console.log(myForm.elements[i].value);
    }

JSFIDDLE : http://jsfiddle.net/rng0hpss/


It is also possible to use this:

var user_name = document.forms[0].elements[0];
var user_email = document.forms[0].elements[1];
var user_message = document.forms[0].elements[2];

All the elements of forms are stored in an array by Javascript. This takes the elements from the first form and stores each value into a unique variable.


Try this to get all the form fields.

var fields = document['formName'].elements;

If you only want form elements that have a name attribute, you can filter the form elements.

const form = document.querySelector("your-form")
Array.from(form.elements).filter(e => e.getAttribute("name"))