1

I have here a div

 <div id='myDiv'>

 </div>

And a button with input type text

  <input id='myNumber' type='text'>
  <button id=myBtn''>Multiply</button>

my script to add an onclick

 <script>
 var myDiv = document.getElementById(''myDiv");
 var myNumber = 
 document.getElementById(''myNumber");
 var myBtn = document.getElementById(''myBtn");
 myBtn.onclick = function(){

       }
  </script>

How can i insert 5 input type text inside myDiv if the value in myText is 5

2 Answers2

1

You can get the count and use the append() to append the input to #myDIv. See the snippet below.

var myDiv = document.getElementById('myDiv');
var input = document.getElementById('myNumber');

function addInput() {
  let count = parseInt(input.value);
  if (!isNaN(count)) {
    myDiv.innerHTML = "";
    for (let i = 0; i < count; i++) {
      let input = document.createElement('input');
      input.type = "text";
      myDiv.append(input);
    }
  }
}
<div id='myDiv'>

</div>

<input id='myNumber' type='text'>
<button onclick="addInput()">Multiply</button>
Nidhin Joseph
  • 9,981
  • 4
  • 26
  • 48
0

You can use onclick() function directly on the button element. Also, check for the negative values to prevent from adding the elements on the div.

function addElement() {
  let count = document.getElementById('myNumber').value;;
  if (!isNaN(count) && count > 0) {
    myDiv.innerHTML = "";
    for (let i = 0; i < count; i++) {
      let div = document.createElement('input');
      myDiv.append(div);
    }
  }
};
<div id='myDiv'>
</div>
<input id='myNumber' type='text'>
<button id='myBtn' onclick="addElement()">Multiply</button>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62