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?
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.
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.
The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With