最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get all input field names from an HTML form with code - Stack Overflow

programmeradmin7浏览0评论

I have an HTML input form to write data into my Google spreadsheet. I want to assign heading names to the spreadsheet columns. I need to get the name attributes of all the input fields for this.

How can I get the name attribute from each input tag in my HTML form?

I have an HTML input form to write data into my Google spreadsheet. I want to assign heading names to the spreadsheet columns. I need to get the name attributes of all the input fields for this.

How can I get the name attribute from each input tag in my HTML form?

Share Improve this question edited Aug 17, 2020 at 8:13 ziganotschka 26.8k2 gold badges17 silver badges34 bronze badges asked Feb 12, 2015 at 22:09 Kyle UptonKyle Upton 1631 gold badge1 silver badge8 bronze badges 1
  • Unclear what you're trying to do. Maybe include some code – AshClarke Commented Feb 12, 2015 at 23:16
Add a ment  | 

3 Answers 3

Reset to default 13

This code assumes that the HTML input tags that you want to get already have a name attribute. You can get all the INPUT elements by tag name, the tag name being "input". Then loop through them and test for which input elements have a name attribute and get the name attribute settings:

<html>
<body>

<p>Inputs:</p>

  <input type="text" value="coffee" name="beverage">
  <input type="text" value="Chef salad" name="salad">
  <input type="text" value="Beef" name="mainCourse">
  <input type="text" value="Cake" name="desert">

<p>Click the button to display the value of the inputs</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var arrayOfInputNames,elmts,L;

  elmts = document.getElementsByTagName("input");
  
  console.log("elmts: " + elmts);
  console.log("Number of inputs: " + elmts.length);

  arrayOfInputNames = [];

  L = elmts.length;

  for (var i = 0; i < L; i++) {
    console.log("i: " + i);
    console.log("value: " + elmts[i].name);
    
    arrayOfInputNames.push(elmts[i].name);
  }

  console.log(arrayOfInputNames);
  document.getElementById("demo").innerHTML = arrayOfInputNames;
}
</script>

</body>
</html>

Get All field name with their corresponding value using javascript as below

var serializeForm = (formElement) => {
    const formData = {};
    const inputs = formElement.elements;  
    for (let i = 0; i < inputs.length; i++) {
      if(inputs[i].name!=="")
          formData[inputs[i].name] = inputs[i].value;
    }
    return formData;
}
let data  = [];
$.each($('#contact :input'),(ind, value) => {
  if (value.tagName !== 'BUTTON') {
    if (value.value === "") {
      alert("Empty Value");
      data = null;
      return false;
    } else {
      data.push(value.id+":"+value.value);
    }
  }
});

Works good for my use in a small form in bo with node. #contact is the form ID...

发布评论

评论列表(0)

  1. 暂无评论