6

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?

1
  • Unclear what you're trying to do. Maybe include some code Commented Feb 12, 2015 at 23:16

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

Comments

3

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;
}

2 Comments

How to use this?
Hi, @Codelaby ! You'll have to add the above JavaScript to a Web page that already has a form.
0
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 combo with node. #contact is the form ID...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.