简体   繁体   中英

Repeating a div based on user input (JavaScript solution preferred)

Looking for the simplest implementation of the following problem:

I have a user input number field like:

<input type="number" id="numInput" name="numInput" value="1" onchange="myFunc()">

<div id="demo">*** TEST ***</div>

I want to replicate the #demo div based on the #numInput value entered by the user, eg if the user enters '5', there would be five #demo divs displayed on the page. At the moment, I'm using the following function:

function myFunc() {
  var newArray = [];
  var numInput = document.getElementById('numInput').value;
  var x = document.getElementById('demo').innerHTML;

  for(var i=0; i<numInput; i++) {
    newArray.push(x);
  }

  document.getElementById('demo').innerHTML = newArray;
}

but this is adding to the existing array rather than outputting the exact number of divs based on user input. Please advise. Thanks.

There should not be multiple same id values.

 function myFunc() { let numInput = document.getElementById("numInput"); while (numInput.nextSibling) { numInput.nextSibling.remove(); } let numInputval = document.getElementById('numInput').value; for(var i=numInputval; i>0; i--) { var newDiv = document.createElement('div'); newDiv.setAttribute('id', 'demo' + i); newDiv.innerHTML = '*** TEST ***'; numInput.parentNode.insertBefore(newDiv, numInput.nextSibling); } }
 <input type="number" id="numInput" name="numInput" onchange="myFunc()">

+Edit You can also manipulate <form> with javascript.

 function myFunc() { let numInput = document.getElementById("numInput"); while (numInput.nextSibling) { numInput.nextSibling.remove(); } let numInputval = document.getElementById('numInput').value; for(var i=numInputval; i>0; i--) { var newInput = document.createElement('input'); newInput.setAttribute('id', 'demoInput' + i); newInput.setAttribute('type', 'text'); newInput.setAttribute('name', 'demoInputName' + i); newInput.setAttribute('onchange', 'myFormChangeListener(this)'); numInput.parentNode.insertBefore(newInput, numInput.nextSibling); numInput.parentNode.insertBefore(document.createElement('br'), numInput.nextSibling); } } function myFormChangeListener(element) { console.log(element); console.log(element.value); myForm.action = 'http://the.url/'; myForm.method = 'post'; console.log(myForm); //myForm.submit; }
 <form id="myForm"> <input type="number" id="numInput" name="numInput" onchange="myFunc()"> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM