AEnimaH AEnimaH - 6 months ago 12
HTML Question

Getting values from html elements in javascript

I have this dynamic form where I put every value of the input in an array. The problem is that I'm not able to get all these items in a javascript function.

My html form:

<form>
<input type="text" placeholder="Name 1" id="myInputs[]">
<input type="text" placeholder="Name 2" id="myInputs[]">
<input type="text" placeholder="Name 3" id="myInputs[]">
<input type="text" placeholder="Name 4" id="myInputs[]">
<input type="text" placeholder="Name 5" id="myInputs[]">
<input type="text" placeholder="Name 6" id="myInputs[]">
<button onclick="process()">Next</button>
</form>


My script function

function process(){
var name = document.getElementById("myInputs[]").value;
var name1 = name[0];
}


In this function I get the first array entry, but this does only return the first character of the first entry.

Answer

Id's should always be unique.

The id global attribute defines a unique identifier (ID) which must be unique in the whole document. Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).

You should consider using name="myInputs[]" instead.

That way you could just do document.getElementsByName("myInputs[]") and iterate over the NodeList.

function process() {
  var allInputs = document.getElementsByName("myInputs[]");
  var name1 = allInputs[0].value; // This is the Value of the first Input
}
<form>
  <input type="text" placeholder="Name 1" name="myInputs[]">
  <input type="text" placeholder="Name 2" name="myInputs[]">
  <input type="text" placeholder="Name 3" name="myInputs[]">
  <input type="text" placeholder="Name 4" name="myInputs[]">
  <input type="text" placeholder="Name 5" name="myInputs[]">
  <input type="text" placeholder="Name 6" name="myInputs[]">
  <button onclick="process()">Next</button>
</form>