manraj82
manraj82

Reputation: 6325

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?

Upvotes: 91

Views: 233975

Answers (20)

ggorlen
ggorlen

Reputation: 57446

.elements and Object.fromEntries(new FormData(form)) have been mentioned, but here's a runnable, complete example to supplement the existing answers:

document.querySelector("form").addEventListener("submit", event => {
  event.preventDefault();

  // work with individual entries:
  const {elements} = event.target;
  const username = elements["username"].value;
  const password = elements["password"].value;
  console.log({username, password});

  // or extract all named input entries:
  const data = Object.fromEntries(new FormData(event.target));
  console.log(data);
});
<form>
  <div>
    <label for="username">Username:</label>
    <input id="username" name="username" required />
  </div>
  <div>
    <label for="password">Password:</label>
    <input id="password" name="password" required />
  </div>
  <input type="submit" value="Login" />
</form>

The name="" fields are the keys in the elements object.

Upvotes: 0

David Spector
David Spector

Reputation: 1677

This answer generates a JavaScript Object containing all the form field names and values, in correct order. It combines several of the answers here.

It works by first finding the form element. Then it generates a NodeList of all the form's elements that have a NAME attribute. Then it paws through those elements, constructing the Object from the names and values of each element.

This technique is useful for submitting a form on the same page (using fetch if you do want to use PHP), without using GET or POST to do a page request. The tab's history is not changed, and no redirection is needed.

Here is a full, working example:

<!DOCTYPE html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1"> 
</head>
<body>
<form id=main>
    Enter name:
        <input type=text name=fname value=MyName>
    <select name=fselect rows=1>
        <option selected>MyChoice</option>
    </select><br>
    <textarea name=ftextarea>MyTextarea</textarea>
    <input type=button name=fbutton
        value=SubmitButton onclick='Submit()'>
</form>

<script>
function Submit()
    {
    const main = document.getElementById('main');
    const nodeList = main.querySelectorAll('[name]');
    const fields = {};
    Array.from(nodeList).forEach(node =>
        {fields[node.name] = node.value;});

    console.log(fields);
    /* Shows: {fname: 'MyName', fselect: 'MyChoice',
        ftextarea: 'MyTextarea', fbutton: 'SubmitButton'} */
    } // Submit
</script>
</body>
</html>

Upvotes: 0

ccpizza
ccpizza

Reputation: 31841

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.

Upvotes: 4

nikk wong
nikk wong

Reputation: 8710

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: "[email protected]",
   password: "mypassword"
}

Upvotes: 8

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

Upvotes: 0

Navigatron
Navigatron

Reputation: 2115

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.

Upvotes: 11

Mateus Queir&#243;s
Mateus Queir&#243;s

Reputation: 41

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.

Upvotes: 3

Eduardo Ver&#237;ssimo
Eduardo Ver&#237;ssimo

Reputation: 491

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)
}

Upvotes: 27

WoodrowShigeru
WoodrowShigeru

Reputation: 1606

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'));

Upvotes: 0

EarlyCoder
EarlyCoder

Reputation: 1313

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

Upvotes: 1

epascarello
epascarello

Reputation: 207557

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

Update for 2020:

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

Upvotes: 9

alistair
alistair

Reputation: 575

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);

Upvotes: 12

Shiplu
Shiplu

Reputation: 516

Try this to get all the form fields.

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

Upvotes: 5

Tim Down
Tim Down

Reputation: 324737

document.getElementById("someFormId").elements;

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

Upvotes: 177

Raphael Rafatpanah
Raphael Rafatpanah

Reputation: 20007

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"))

Upvotes: 2

Joshua
Joshua

Reputation: 866

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.

Upvotes: 5

Arsalan Sheikh
Arsalan Sheikh

Reputation: 627

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/

Upvotes: 7

esvendsen
esvendsen

Reputation: 1510

document.forms["form_name"].getElementsByTagName("input");

Upvotes: 37

Kasim Muflahi
Kasim Muflahi

Reputation: 351

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.

Upvotes: 25

Matt Ball
Matt Ball

Reputation: 360066

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');
}

Upvotes: 1

Related Questions