Get all input field names from an HTML form with code

Kyle Upton picture Kyle Upton · Feb 12, 2015 · Viewed 10.1k times · Source

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?

Answer

Alan Wells picture Alan Wells · Feb 13, 2015

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>