get all the elements of a particular form
JavascriptJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
document.getElementById("someFormId").elements;
This collection will also contain <select>
, <textarea>
and <button>
elements (among others), but you probably want that.
Solution 2 - Javascript
document.forms["form_name"].getElementsByTagName("input");
Solution 3 - Javascript
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.
Solution 4 - Javascript
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)
}
Solution 5 - Javascript
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.
Solution 6 - Javascript
var inputs = document.getElementById("formId").getElementsByTagName("input");
var inputs = document.forms[1].getElementsByTagName("input");
Update for 2020:
var inputs = document.querySelectorAll("#formId input");
Solution 7 - Javascript
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);
Solution 8 - Javascript
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/
Solution 9 - Javascript
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.
Solution 10 - Javascript
Try this to get all the form fields.
var fields = document['formName'].elements;
Solution 11 - Javascript
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.
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.
Solution 12 - Javascript
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.
Solution 13 - Javascript
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"))
Solution 14 - Javascript
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"
}
Solution 15 - Javascript
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');
}
Solution 16 - Javascript
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
Solution 17 - Javascript
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'));
Solution 18 - Javascript
const contactForm = new FormData("formLocatorIdIsAdviceableAsTheLocator");
The above is handy regardless of context(framework or pure js because):
- It returns you an object using the form input-names as keys and the element-value as value
- You can add your own object: contactForm.append(yourKey,yourValye)
For more: https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData