jQuery -如何在保留先前输入值的同时添加输入



我想使用jQuery添加新的输入,但是,在点击添加输入后,使用jQuery在下面添加另一个这样的元素,它删除了之前的输入。

var num = 2;
document.getElementById('add').addEventListener("click", addInput);
function addInput() {
var newInput = `
<div>
<input type="date" id="start" name="avail[startdate${num}] value="" min="" max="" />
<input type="range" name = "avail[startdate${num}] value="" min="0" max="23" oninput="this.nextElementSibling.value = this.value" >
<output>12</output><span>:00 (GMT+8) </span>
</div>
`
// '<input type="text" name="input'+num+'"/><br> <br>';
document.getElementById('demo').innerHTML += newInput;
num++;
}
document.querySelectorAll('input[type="range"]').forEach((input) => {
input.addEventListener('mousedown', () => window.getSelection().removeAllRanges());
});
<p>Availability</p>
<div id="demo">
<div class="">
<input type="date" id="start" name="avail[startdate1]" value="" min="" max="">
<input type="range" value="" name="avail[startdate1]" min="0" max="23" oninput="this.nextElementSibling.value = this.value">
<output>12</output><span>:00 (GMT+8) </span>
<br>
</div>
</div>
<input type="button" id="add" value="Add input" />

捕获元素(在示例中为parent)。使用insertAdjacentHTML,您可以在捕获元素上附加新元素,而不会丢失先前的范围状态。

的例子:

var num = 2;
document.getElementById('add').addEventListener("click", addInput);
function addInput() {
var parent = document.getElementById('demo');
var newInput = `
<div>
<input type="date" id="start" name="avail[startdate${num}] value="" min="" max="" />
<input type="range" name = "avail[startdate${num}] value="" min="0" max="23" oninput="this.nextElementSibling.value = this.value" >
<output>12</output><span>:00 (GMT+8) </span>
</div>
`
// '<input type="text" name="input'+num+'"/><br> <br>';
parent.insertAdjacentHTML('beforeend', newInput);
num++;
}
document.querySelectorAll('input[type="range"]').forEach((input) => {
input.addEventListener('mousedown', () => window.getSelection().removeAllRanges());
});
<p>Availability</p>
<div id="demo">
<div class="">
<input type="date" id="start" name="avail[startdate1]" value="" min="" max="">
<input type="range" value="" name="avail[startdate1]" min="0" max="23" oninput="this.nextElementSibling.value = this.value">
<output>12</output><span>:00 (GMT+8) </span>
<br>
</div>
</div>
<input type="button" id="add" value="Add input" />

通过使用document.getElementById('demo').innerHTML,您正在更新演示中的当前HTMLdiv.你可以使用另一个id或代替innerHTML,你可以使用jQueryappend

最新更新