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?
- Unclear what you're trying to do. Maybe include some code – AshClarke Commented Feb 12, 2015 at 23:16
3 Answers
Reset to default 13This 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...