Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all input field names from an HTML form with code

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?

like image 245
Kyle Upton Avatar asked Feb 12 '15 22:02

Kyle Upton


People also ask

How do I get all input elements?

You can get a NodeList of all of the input elements via getElementsByTagName (DOM specification, MDC, MSDN), then simply loop through it: var inputs, index; inputs = document. getElementsByTagName('input'); for (index = 0; index < inputs.

How do you collect input in HTML?

Using HTML forms, you can easily take user input. The <form> tag is used to get user input, by adding the form elements. Different types of form elements include text input, radio button input, submit button, etc. Let's learn about the <input> tag, which helps you to take user input using the type attribute.

Which attribute is required for all input fields in a HTML form?

The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form.

How do I show the results of a form in HTML?

The formtarget attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form. The formtarget attribute overrides the target attribute of the <form> element. Note: The formtarget attribute is new for the <input> element with type="submit" in HTML5.


1 Answers

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>
like image 132
Alan Wells Avatar answered Nov 14 '22 22:11

Alan Wells