85
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?

user664833
  • 18,397
  • 19
  • 91
  • 140
manraj82
  • 5,929
  • 24
  • 56
  • 83

18 Answers18

166
document.getElementById("someFormId").elements;

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

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • It appears that document.getElementById("someFormId") also works. Any particular reason for adding .elements at the end? – Andrew Dec 09 '13 at 08:42
  • 2
    @Andrew: My intention was that "someFormId" is the ID of a `
    ` element, not an input. `elements` is a property of a form element; it's a collection of elements within the form. See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement.elements
    – Tim Down Dec 09 '13 at 09:36
  • 1
    > ok, i understand what .elements is. So should I use it, if it works even without it? Maybe adding .elements selects less nodes and thus you get better performance? – Andrew Dec 09 '13 at 12:56
  • 1
    @Andrew: Works how? You can access form inputs by name as properties of the form but there are problems with that: first, the form has other properties that could potentially clash (for example, an input with name "action" would not be reflected as a property of the form because the form already has an `action` property that reflects its `action` attribute). Second, there is no easy, reliable way to enumerate the inputs as properties of the form object and certainly not in order. `elements` has numeric properties in document order in addition to the properties corresponding to input names. – Tim Down Dec 09 '13 at 14:52
  • Thanks, i think you are right. It's better to select with .elements – Andrew Dec 09 '13 at 16:10
  • how to filter the inputs from that list – serge Oct 21 '22 at 08:08
36
document.forms["form_name"].getElementsByTagName("input");
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
esvendsen
  • 1,492
  • 1
  • 12
  • 16
24

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.

Kasim Muflahi
  • 341
  • 2
  • 2
20

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)
}
M Code
  • 59
  • 4
11

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);
alistair
  • 565
  • 5
  • 15
11

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.

Eugen Konkov
  • 22,193
  • 17
  • 108
  • 158
Navigatron
  • 2,065
  • 6
  • 32
  • 61
9
var inputs = document.getElementById("formId").getElementsByTagName("input");
var inputs = document.forms[1].getElementsByTagName("input");

Update for 2020:

var inputs = document.querySelectorAll("#formId input");
epascarello
  • 204,599
  • 20
  • 195
  • 236
7

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="johndoe@test.com"/>
        <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/

Arsalan Sheikh
  • 607
  • 7
  • 10
  • 1
    it will return [array of `input` elements](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements), except `type="image"` – Mike Datsko Jun 25 '17 at 20:42
7

Loosely relevant but if you'd like to get all of the form items in an object you can:

Object.fromEntries(new FormData(document.querySelector('form')).entries())

Which yields

{
   email: "thao@le.com",
   password: "mypassword"
}
nikk wong
  • 8,059
  • 6
  • 51
  • 68
5

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.

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
Joshua
  • 818
  • 11
  • 12
  • Hey, Here what is happening I tried to return if the id matches to a value then it should return which will break the loop and will return the result. But it is not doing such thing. – ganesh kaspate May 11 '18 at 10:48
  • @ganeshkaspate unfortunately it is not possible to stop the slice foreah loop with a break or return, however there is a work around by throwing and catching an exception. Once you find the element you are looking for, you throw and exception to break out of the loop, then catch it so as not to cause any error. try{ [].slice.call(theForm).forEach(function (el, i){ console.log(el.id); if (el.id == 'e2') throw new Exception; }); }catch(err){ } Again, if you know the id of the element you are looking for, why not just select it directly rather than going through a loop – Joshua May 13 '18 at 16:07
5

Try this to get all the form fields.

var fields = document['formName'].elements;
Shiplu
  • 460
  • 6
  • 13
4

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 (if there is one, of course). That means that once you have a field 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.

function doLogin(e) {
    e = e || window.event;
    e.preventDefault();
    // e.target is the submit button
    var form = e.target.form;

    if (form.login.value && form.password.value) {
        alert("Submitting form — user:" + form.login.value + " password:" + form.password.value);
        form.submit();
    } else {
        alert('Please fill in the form!');
    }
}
    
<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>
</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.

ccpizza
  • 28,968
  • 18
  • 162
  • 169
3

You can select by simply taking all elements that contain the attribute name

let form = document.querySelector("form");

form.querySelectorAll("[name]");

This will return all relevant elements of the form.

2

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"))
Raphael Rafatpanah
  • 19,082
  • 25
  • 92
  • 158
1

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');
}
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
1
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

EarlyCoder
  • 1,213
  • 2
  • 18
  • 42
0

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'));
WoodrowShigeru
  • 1,418
  • 1
  • 18
  • 25
0
const contactForm = new FormData("formLocatorIdIsAdviceableAsTheLocator");

The above is handy regardless of context(framework or pure js because):

  1. It returns you an object using the form input-names as keys and the element-value as value
  2. You can add your own object: contactForm.append(yourKey,yourValye)

For more: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData

Emmanuel Onah
  • 580
  • 4
  • 8