简体   繁体   English

根据用户输入重复 div(首选 JavaScript 解决方案)

[英]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.我想根据用户输入的#numInput 值复制#demo div,例如,如果用户输入'5',页面上将显示五个#demo div。 At the moment, I'm using the following function:目前,我正在使用以下 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.但这会添加到现有数组中,而不是根据用户输入输出确切数量的 div。 Please advise.请指教。 Thanks.谢谢。

There should not be multiple same id values.不应有多个相同的 id 值。

 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. +Edit您还可以使用 javascript 操作<form>

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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