1

I'm trying to generate multiple <input type=text> based on user's request. In another word, the user enters a number, like n and therefore <input type=text> going to appear on the screen for n times.

Here is my code, which somehow is based on this answer, but doesn't work properly for me.

function generateInputs() {
  var count = document.getElementById("test");

  for (i = 0; i < Number(count); i++) {
      var input = document.createElement("input");
      input.setAttribute('type', 'text');
      var x = document.getElementsByClassName("testClass");
      x[0].appendChild(input)
  }
}
<body>
    <input type="number" id="test" min="2" max="20" required>
    <button onclick="generateInputs()">Test</button>

    <div class="testClass">    
    </div>
</body>

I expect to see for example 2 <input ...>, if the user enters 2 and clicks the button, but nothing is shown. Would you mind let me know about my mistake?

Mamun
  • 66,969
  • 9
  • 47
  • 59
Amid
  • 442
  • 2
  • 8
  • 15

2 Answers2

5

You're really close. The thing is that you're not getting the count correctly. You're getting the element, not its value. Add .value:

var count = document.getElementById("test").value;
// ----------------------------------------^^^^^^

There are a few other things to consider as well:

  1. You're not declaring i, so the code is falling prey to what I call The Horror of Implicit Globals. Declare your variables. :-)

  2. Probably best to convert value from string to number just once, rather than on each iteration of the loop.

  3. Similarly, there's no reason to go get the .testClass elements every time in the loop.

  4. type is reflected as an element property, so if you like, instead of

    input.setAttribute('type', 'text');
    

    you can use

    input.type = 'text';
    
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Off topic but I find it incredible that after 20+ years `document.getElementById` is still being used. I wouldn't be surprised if I saw it being used in 2030 or beyond. – Malekai Jul 14 '19 at 18:37
  • I'd like to add that most of the problems listed in this answer could be avoided by using jshint and strict(er) type checking (via TypeScript or `.jshintrc`). – Malekai Jul 14 '19 at 18:40
2

You have to take the value from the input element. You also do not need to get the element (to where the append is to be made) in each iteration:

var count = document.getElementById("test").value;

function generateInputs() {
  var count = document.getElementById("test").value;
  var x = document.getElementsByClassName("testClass");
  for (i = 0; i < Number(count); i++) {
    var input = document.createElement("input");
    input.setAttribute('type', 'text');
    x[0].appendChild(input)
  }
}
<body>
  <input type="number" id="test" min="2" max="20" required />
  <button onclick="generateInputs()">Test</button>
  <div class="testClass"></div>
</body>
Malekai
  • 4,765
  • 5
  • 25
  • 60
Mamun
  • 66,969
  • 9
  • 47
  • 59