Amid
Amid

Reputation: 621

How can I generate multiple inputs upon user's request?

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?

Upvotes: 1

Views: 202

Answers (2)

Mamun
Mamun

Reputation: 68933

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>

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1074248

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

Upvotes: 5

Related Questions