JavaScript新秀......
我正在尝试构建一个表单,其中我有一个特定字段,我希望人们能够添加多达4个字段。我想我设法做了那部分(虽然可能是非常笨重的代码)但我不知道如何使删除功能工作。挑战在于,当有人点击减号时,我想删除最后创建的字段和最后一个字段。
感谢您的帮助!
HTML:
<form action="">
<div class="form-element">
<input type="text" name="Name" id="" placeholder="Full Legal Name">
</div>
<h3>Broker Principal(s)</h3>
<div class="form-element">
<input type="text" name="Name" id="" placeholder="Broker Principal">
</div>
<div class="form-element" id="addField">
</div>
<i id="add" class="fa fa-plus-circle fa-2x"></i>
<i id="add" class="fa fa-minus-circle fa-2x hidden minus"></i>
</form>
JS:
var plus = document.getElementById("add");
var minus = document.querySelector(".minus");
var array = [1,2,3,4,5];
var counter = 2;
var field = document.getElementById("addField");
plus.addEventListener("click", function(){
if(counter !== 0){
field.insertAdjacentHTML("beforeend", '<div id="bp' + counter + '" class="form-element fadeOutIn">' + '<input type="text" name="Broker Principal ' + counter + '" id="" placeholder="Broker Principal ' + counter + '">' + "</div>");
minus.classList.remove("hidden");
counter = (counter + 1) % array.length;
}
});
CSS:
body {
font-size: 17px;
}
input {
padding: 10px 20px;
font-size: 17px;
}
.form-element {
display: block;
margin: 8px 0;
}
i {
color: #FDB813;
transition: all 0.3s;
cursor: pointer;
}
i:hover {
color: #FEC849;
}
@keyframes fadeOutIn {
0% {opacity: 0;}
50% {opacity: 0.4;}
100% {opacity: 1;}
}
.fadeOutIn {
animation-name: fadeOutIn;
animation-duration: 400ms;
}
.hidden {
display: none;
}
答案 0 :(得分:0)
你可以做这样的事情
minus.addEventListener("click", function(){
var form = document.getElementById('addField');
form.removeChild(form.childNodes[form.childNodes.length-1]);
}