您好我有以下代码..我们可以动态添加文本输入
我想要做的是添加文本输入和选项以删除除默认的第一个
之外的文本输入添加文字输入正在运行但不是删除文字输入
https://jsfiddle.net/ob8n48cg/20/
<script>
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function removeInput(divName){
var newdiv = document.removeElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).removeChild(newdiv);
}
</script>
<form method="POST">
<div id="dynamicInput">
Entry 1<br><input type="text" name="myInputs[]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
<button onclick="removeInput('dynamicInput');">Remove Input</button>
</form>
答案 0 :(得分:2)
试试这个
var counter = 1;
var limit = 3;
function addInput(divName){
if (counter === limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function removeInput(event,divName){
event.preventDefault()
var parent = document.getElementById(divName)
parent.removeChild(parent.lastElementChild)
counter--
}
<form>
<div id="dynamicInput">
<div>
Entry 1<br><input type="text" name="myInputs[]">
</div>
</div>
<input type="button" value="Add another text input" onclick="addInput('dynamicInput');">
<button onclick="removeInput(event,'dynamicInput');">Remove Input</button>
</form>
答案 1 :(得分:0)
运行代码时,请务必检查浏览器中的控制台窗口,检查是否显示removeInput函数中有错误:
(index):75 Uncaught ReferenceError: newdiv is not defined
at removeInput ((index):75)
at HTMLButtonElement.onclick ((index):87)
removeInput @ (index):75
onclick @(index):87
确保在删除功能以及添加功能中定义newdiv!