我有这样一个表单,它将根据在这个表单中输入的总价值生成表单的数量。
<form>
<input type="Number" name="delivery">
</form>例如,如果用户填写了输入3,它将实时自动生成3个新表单。
<form>
<input type="Number" name="delivery">
<input type="text" name="destination">
<input type="text" name="destination">
<input type="text" name="destination">
</form>我的应用程序不使用jquery,所以我必须在普通的js中这样做。请引导我这样做
发布于 2020-06-23 15:32:43
像这样的东西可能会起作用:
const input = document.getElementById('delivery');
const form = document.getElementById('form');
input.addEventListener('change', () => {
form.innerHTML = '';
for (i = 0; i < parseInt(input.value); i++) {
let formInput = document.createElement('input');
formInput.setAttribute('type', 'text')
formInput.setAttribute('name', 'destination');
form.appendChild(formInput);
}
})<input type="Number" id="delivery">
<form id="form">
</form>
当数字发生变化时,将相应地添加输入。
发布于 2020-06-23 15:14:56
您可以使用
let inputElem = document.createElement('input');若要创建新的输入元素和
document.querySelector('form').appentChild(inputElem); 将此新输入项追加到父窗体
您可以使用for循环来创建任意数量的元素。
像这样
<form>
<input type="Number" name="delivery" onchange="createInput(this)">
<div id='dynamic'>
</div>
</form>
<script>
function createInput(elem){
const container = document.getElementById('dynamic');
container.innerHTML = '';
const count = elem.value;
for(let i= 0; i< count;i++){
const newInput = document.createElement('input'); container.appendChild(newInput);
}
}
</script>https://stackoverflow.com/questions/62538001
复制相似问题