admin管理员组

文章数量:1131223

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?

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?

Share Improve this question edited Jan 20, 2018 at 22:07 user664833 19.5k20 gold badges94 silver badges147 bronze badges asked Dec 13, 2010 at 16:44 manraj82manraj82 6,28524 gold badges58 silver badges85 bronze badges
Add a comment  | 

19 Answers 19

Reset to default 177
document.getElementById("someFormId").elements;

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

document.forms["form_name"].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)
}

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.

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

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.

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

Update for 2020:

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

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

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/

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.

Try this to get all the form fields.

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

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.

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.

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

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

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

.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();
  const {elements} = event.target;

  // work with individual entries:
  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.

本文标签: javascriptget all the elements of a particular formStack Overflow