get all the elements of a particular form

2020-02-08 03:13发布

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
12条回答
家丑人穷心不美
2楼-- · 2020-02-08 03:36

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.

查看更多
闹够了就滚
3楼-- · 2020-02-08 03:39

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"))
查看更多
Fickle 薄情
4楼-- · 2020-02-08 03:41

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);
查看更多
戒情不戒烟
5楼-- · 2020-02-08 03:45
var inputs = document.getElementById("formId").getElementsByTagName("input");
var inputs = document.forms[1].getElementsByTagName("input");
查看更多
Rolldiameter
6楼-- · 2020-02-08 03:47

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.

查看更多
劫难
7楼-- · 2020-02-08 03:49

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.

查看更多
登录 后发表回答