Sam Ram San Sam Ram San - 6 months ago 7
Javascript Question

Can some one tell me why is this not working

I have a form where I'd like to add new input fields, and I'm sure I almost got it but something's not working because the name attribute is not auto incrementing.

<button onclick="afunction()">Insert New Text Field</button>
<script>
function afunction() {
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", "something cool");
for (i = 0; i < 12; i++) {
x.setAttribute("name","input"+i);
}
document.body.appendChild(x);
}
</script>


Thank you for your valuable help.

Answer

Your for-loop looping from i = 0 to 11 does not make sense. With each loop iteration, you just override the previously set name attribute of the same element x and finally end up with "input" + 11 as the name.

You need to move the declaration of your counter variable (I called it numInputs) outside your function and only increment it by one for each function call, e. g. as follows:

var numInputs = 0;

function addInput() {
  var input = document.createElement("input");
  input.setAttribute("type", "text");
  input.setAttribute("value", "something cool");
  input.setAttribute("name", "input" + numInputs);
  document.body.appendChild(input);
  numInputs++;
  
  // Debug output:
  console.log(document.body.querySelectorAll('input[name^=input]'));
}
<button onclick="addInput()">Insert New Text Field</button>

If you feel more confident in your Javascript programming skills, you can encapsulate your counter variable numInputs and the addInput function as a closure within an Immediately-Invoked Function Expression:

const addInput = (function() {
  var numInputs = 0;
  return function() {
    var input = document.createElement("input");
    input.setAttribute("type", "text");
    input.setAttribute("value", "something cool");
    input.setAttribute("name", "input" + numInputs);
    document.body.appendChild(input);
    numInputs++;

    // Debug output:
    console.log(document.body.querySelectorAll('input[name^=input]'));
  }
})();
<button onclick="addInput()">Insert New Text Field</button>