使用 JavaScript 或 Jquery 动态删除 html 输入字段
dynamically delete html input field using JavaScript or Jquery
我有一个包含 1 select 输入字段的表单。
当我在select字段中的选项之一select。我默认创建一个包含文本输入字段的 部分、一个关闭按钮和一个添加字段按钮以添加更多输入文本字段。
一切正常,但我不确定如何删除动态创建的输入字段。当我单击旁边的删除按钮时,我不确定要使用 id 或 class 或名称属性或 what 来查找和删除输入字段。
我的代码
HTML 代码
<div class="form-group">
<div class="row">
<div class="col-md-12" id="extraFieldsLabelHolder"></div>
</div>
<div class="row" id="extraFields">
<!-- here I can add as many custom fields I want -->
</div>
</div>
JS 代码
function addFields(){
var selectVal = document.getElementById('type_id').value;
if(selectVal === 'checkbox' || selectVal === 'radio'){
if(!document.getElementById("addBtn")){
//add input fields
var extraFieldDIV = document.getElementById("extraFieldsLabelHolder");
var fieldLabel = document.createElement("label");
fieldLabel.setAttribute("for", "extraFields");
fieldLabel.setAttribute('id', "extraFieldsLabel")
fieldLabel.textContent = "Add Custom Field Options:";
extraFieldDIV.appendChild(fieldLabel);
//IT MAY LOOK COMPLEX BUT ITS FAIRLY STRAIGHTFORWARD
//Code below creates mainDiv and a Div which holds input and a delete btn
var fieldArea = document.getElementById('extraFields');
var mainDiv = document.createElement("div");
mainDiv.setAttribute("class", "input_field col-md-4");
mainDiv.setAttribute("style", "margin-bottom:10px;");
fieldArea.appendChild(mainDiv);
var div = document.createElement("div");
div.setAttribute("class", "input-group");
mainDiv.appendChild(div);
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("class", "form-control input_field");
input.setAttribute("placeholder", "Enter value...");
input.setAttribute("name", "extras[]");
div.appendChild(input);
var span = document.createElement("span");
span.setAttribute("class", "input-group-btn");
div.appendChild(span);
var closeBtn = document.createElement("button");
closeBtn.setAttribute("type", "button");
closeBtn.setAttribute("class", "btn btn-danger");
//YOU CAN SEE HERE I PASS ONCLICK METHOD but not sure what to do NEXT
//ALL I GET IS INFO OF A DELETE BUTTON and Not the actual DIV which contains input field too.
closeBtn.setAttribute("onclick", "removeInputField(this)");
span.appendChild(closeBtn);
var iElement = document.createElement("i");
iElement.setAttribute("class", "pe-7s-close");
iElement.setAttribute("style", "font-size:20px");
closeBtn.appendChild(iElement);
var btnArea = document.getElementById('addFieldBtnHolder');
var btn = document.createElement("button");
btn.setAttribute("type", "button");
btn.setAttribute("class", "btn btn-primary");
btn.setAttribute("style", "margin-top:15px;");
btn.setAttribute("onclick", "addInputField()");
btn.textContent = "Add Field";
btn.setAttribute('id', "addBtn");
btnArea.appendChild(btn);
}
}else{
if(document.getElementById("addBtn")) {
document.getElementById("extraFieldsLabel").remove();
document.getElementById("addBtn").remove();
var inputs = document.getElementsByClassName('input_field');
for(var i = 0; i < inputs.length; i++){
inputs[i].remove();
}
}
}
}
function addInputField(){
console.log("test2");
var fieldArea = document.getElementById('extraFields');
var mainDiv = document.createElement("div");
mainDiv.setAttribute("class", "input_field col-md-4");
mainDiv.setAttribute("style", "margin-bottom:10px;");
fieldArea.appendChild(mainDiv);
var div = document.createElement("div");
div.setAttribute("class", "input-group");
mainDiv.appendChild(div);
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("class", "form-control input_field");
input.setAttribute("placeholder", "Enter value...");
input.setAttribute("name", "extras[]");
div.appendChild(input);
var span = document.createElement("span");
span.setAttribute("class", "input-group-btn");
div.appendChild(span);
var closeBtn = document.createElement("button");
closeBtn.setAttribute("type", "button");
closeBtn.setAttribute("class", "btn btn-danger");
closeBtn.setAttribute("onclick", "removeInputField(this)");
span.appendChild(closeBtn);
var iElement = document.createElement("i");
iElement.setAttribute("class", "pe-7s-close");
iElement.setAttribute("style", "font-size:20px");
closeBtn.appendChild(iElement);
}
//WHAT LOGIC DO I PUT HERE TO DELETE THE DIV CONTAINING input and delete button?
function removeInputField (selectedField) {
console.log("this: ", selectedField.value);
}
你可以使用 closest()
.
但它只适用于现代浏览器。破解你可以阅读 here
function removeInputField (selectedField) {
selectedField.closest('.input_field').remove();
}
查看示例
<style>
.input_field{border: 2px solid red;}
</style>
<script>
function removeInputField (selectedField) {
selectedField.closest('.input_field').remove();
}
</script>
<div>
<div class="input_field">i<button onclick="removeInputField(this);">1</button></div>
<div class="input_field">am<button onclick="removeInputField(this);">2</button></div>
<div class="input_field">another<button onclick="removeInputField(this);">3</button></div>
<div class="input_field">element<button onclick="removeInputField(this);">4</button></div>
</div>
如果您正在使用 Bootstrap(您可能是因为 OP 类 是 BS),那么您可能正在使用 jQuery(BS API 需要 jQuery).所以这个Demo在jQuery。这是它的作用:
开头有 3 个按钮 +⚙
- 添加一个
fieldset.form-group
- CFG 设置(在演示中不起作用)
- SUB将表单数据发送到 live test server
每个fieldset.form-group
有:
3 <input>
1 <textarea>
2 <button>
- CFG 设置(在演示中不起作用)
- DEL删除
fieldset.form-group
每个带有 #id
和 [name]
的元素都有一个唯一的后缀(基于 Date.now()
和 Math.random()
)。
在SUB提交form#frm0
后,一个Link被揭露。
- 单击 link 会将用户滚动到
iframe#response
- `iframe#response 接收并显示来自测试服务器的响应。
参考资料
演示
// When button#ADD is clicked...
$('#ADD').on('click', function(e) {
/* Random number to be interpolated in
|| Template Literal
*/
var ts = Math.round(Date.now() / Math.random() * 11);
/* Template Literal is a string with new
|| syntax and advanced methods and properties
*/
var str = `<fieldset id='setX${ts}' class='SET form-group'><div class="input-group"> <span class="input-group-addon"> <i class="glyphicon glyphicon-user"></i> </span> <input id="name-${ts}" type="text" class="form-control" name="name-${ts}" placeholder="Name"></div><div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i> </span><input id="mail-${ts}" type="email" class="form-control" name="mail-${ts}" placeholder="Email"><span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span><input id="cell-${ts}" type="phone" class="form-control" name="cell-${ts}" placeholder="Phone"></div><div class="input-group pull-right"><div id='setC${ts}' class="btn-group"><button id='CFG${ts}' type="button" class="CFG btn btn-success"> <i class='glyphicon glyphicon-cog'></i> </button> <button id="DEL${ts} "type="button" class="DEL btn btn-danger"> <i class='glyphicon glyphicon-minus'></i> </button></div></div> <span class="input-group-addon" style="height:35px">${ts} <i class="glyphicon glyphicon-info-sign"></i></span><textarea id="info-${ts}" type="text" class="form-control" name="info-${ts}" placeholder="Info" cols='120' rows='4'></textarea></fieldset>`;
// Append TL to DOM (string gets parsed as HTML)
$('#setD').append(str);
// Register the new button.DEL to click event
$('.DEL').on('click', DEL);
});
/* This the callback function for button.DEL
|| click event
*/
function DEL(e) {
// Get the closest fieldset.SET and remove it
var parent = $(this).closest('.SET').remove();
}
// When form#frm0 is submitted show a#RSP
$('#frm0').on('submit', function() {
$('#RSP').show();
});
/* When a#RSP is clicked, scroll to
|| iframe#response.
|| iframe#response receives the server response
|| and displays it.
*/
$("#RSP").click(function() {
$('html, body').animate({
scrollTop: $("#response").offset().top
}, 1000);
});
#RSP {
display: none
}
-
<!DOCTYPE html>
<html lang="en">
<head>
<title>BS Form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<main class="container">
<form id="frm0" action="https://httpbin.org/post" method='post' target='response'>
<div class="input-group pull-right">
<div id='setA' class="btn-group"> <button id='ADD' type="button" class="ADD btn btn-primary"> <i class='glyphicon glyphicon-plus'></i> </button> <button id='CFG' type="button" class="CFG btn btn-success"> <i class='glyphicon glyphicon-cog'></i> </button>
<button id='SUB' type="submit" class="SUB btn btn-warning"> <i class='glyphicon glyphicon-send'></i> </button>
</div>
</div>
<fieldset id='setB' class='form-group'>
<legend>Contact Form</legend>
<a href='#/' id='RSP' class='btn btn-link'>View Response</a>
</fieldset>
<fieldset id='setD' class="form-group"></fieldset>
</form>
<iframe srcdoc='<h1 style="text-align:center;font-family:Consolas">Server Response</h1>' src='about:blank' id='response' name='response' frameborder='1' width='99%' height='300'></iframe>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
我有一个包含 1 select 输入字段的表单。
当我在select字段中的选项之一select。我默认创建一个包含文本输入字段的 部分、一个关闭按钮和一个添加字段按钮以添加更多输入文本字段。
一切正常,但我不确定如何删除动态创建的输入字段。当我单击旁边的删除按钮时,我不确定要使用 id 或 class 或名称属性或 what 来查找和删除输入字段。
我的代码
HTML 代码
<div class="form-group">
<div class="row">
<div class="col-md-12" id="extraFieldsLabelHolder"></div>
</div>
<div class="row" id="extraFields">
<!-- here I can add as many custom fields I want -->
</div>
</div>
JS 代码
function addFields(){
var selectVal = document.getElementById('type_id').value;
if(selectVal === 'checkbox' || selectVal === 'radio'){
if(!document.getElementById("addBtn")){
//add input fields
var extraFieldDIV = document.getElementById("extraFieldsLabelHolder");
var fieldLabel = document.createElement("label");
fieldLabel.setAttribute("for", "extraFields");
fieldLabel.setAttribute('id', "extraFieldsLabel")
fieldLabel.textContent = "Add Custom Field Options:";
extraFieldDIV.appendChild(fieldLabel);
//IT MAY LOOK COMPLEX BUT ITS FAIRLY STRAIGHTFORWARD
//Code below creates mainDiv and a Div which holds input and a delete btn
var fieldArea = document.getElementById('extraFields');
var mainDiv = document.createElement("div");
mainDiv.setAttribute("class", "input_field col-md-4");
mainDiv.setAttribute("style", "margin-bottom:10px;");
fieldArea.appendChild(mainDiv);
var div = document.createElement("div");
div.setAttribute("class", "input-group");
mainDiv.appendChild(div);
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("class", "form-control input_field");
input.setAttribute("placeholder", "Enter value...");
input.setAttribute("name", "extras[]");
div.appendChild(input);
var span = document.createElement("span");
span.setAttribute("class", "input-group-btn");
div.appendChild(span);
var closeBtn = document.createElement("button");
closeBtn.setAttribute("type", "button");
closeBtn.setAttribute("class", "btn btn-danger");
//YOU CAN SEE HERE I PASS ONCLICK METHOD but not sure what to do NEXT
//ALL I GET IS INFO OF A DELETE BUTTON and Not the actual DIV which contains input field too.
closeBtn.setAttribute("onclick", "removeInputField(this)");
span.appendChild(closeBtn);
var iElement = document.createElement("i");
iElement.setAttribute("class", "pe-7s-close");
iElement.setAttribute("style", "font-size:20px");
closeBtn.appendChild(iElement);
var btnArea = document.getElementById('addFieldBtnHolder');
var btn = document.createElement("button");
btn.setAttribute("type", "button");
btn.setAttribute("class", "btn btn-primary");
btn.setAttribute("style", "margin-top:15px;");
btn.setAttribute("onclick", "addInputField()");
btn.textContent = "Add Field";
btn.setAttribute('id', "addBtn");
btnArea.appendChild(btn);
}
}else{
if(document.getElementById("addBtn")) {
document.getElementById("extraFieldsLabel").remove();
document.getElementById("addBtn").remove();
var inputs = document.getElementsByClassName('input_field');
for(var i = 0; i < inputs.length; i++){
inputs[i].remove();
}
}
}
}
function addInputField(){
console.log("test2");
var fieldArea = document.getElementById('extraFields');
var mainDiv = document.createElement("div");
mainDiv.setAttribute("class", "input_field col-md-4");
mainDiv.setAttribute("style", "margin-bottom:10px;");
fieldArea.appendChild(mainDiv);
var div = document.createElement("div");
div.setAttribute("class", "input-group");
mainDiv.appendChild(div);
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("class", "form-control input_field");
input.setAttribute("placeholder", "Enter value...");
input.setAttribute("name", "extras[]");
div.appendChild(input);
var span = document.createElement("span");
span.setAttribute("class", "input-group-btn");
div.appendChild(span);
var closeBtn = document.createElement("button");
closeBtn.setAttribute("type", "button");
closeBtn.setAttribute("class", "btn btn-danger");
closeBtn.setAttribute("onclick", "removeInputField(this)");
span.appendChild(closeBtn);
var iElement = document.createElement("i");
iElement.setAttribute("class", "pe-7s-close");
iElement.setAttribute("style", "font-size:20px");
closeBtn.appendChild(iElement);
}
//WHAT LOGIC DO I PUT HERE TO DELETE THE DIV CONTAINING input and delete button?
function removeInputField (selectedField) {
console.log("this: ", selectedField.value);
}
你可以使用 closest()
.
但它只适用于现代浏览器。破解你可以阅读 here
function removeInputField (selectedField) {
selectedField.closest('.input_field').remove();
}
查看示例
<style>
.input_field{border: 2px solid red;}
</style>
<script>
function removeInputField (selectedField) {
selectedField.closest('.input_field').remove();
}
</script>
<div>
<div class="input_field">i<button onclick="removeInputField(this);">1</button></div>
<div class="input_field">am<button onclick="removeInputField(this);">2</button></div>
<div class="input_field">another<button onclick="removeInputField(this);">3</button></div>
<div class="input_field">element<button onclick="removeInputField(this);">4</button></div>
</div>
如果您正在使用 Bootstrap(您可能是因为 OP 类 是 BS),那么您可能正在使用 jQuery(BS API 需要 jQuery).所以这个Demo在jQuery。这是它的作用:
开头有 3 个按钮 +⚙
- 添加一个
fieldset.form-group
- CFG 设置(在演示中不起作用)
- SUB将表单数据发送到 live test server
- 添加一个
每个
fieldset.form-group
有:3
<input>
1
<textarea>
2
<button>
- CFG 设置(在演示中不起作用)
- DEL删除
fieldset.form-group
每个带有
#id
和[name]
的元素都有一个唯一的后缀(基于Date.now()
和Math.random()
)。在SUB提交
form#frm0
后,一个Link被揭露。- 单击 link 会将用户滚动到
iframe#response
- `iframe#response 接收并显示来自测试服务器的响应。
- 单击 link 会将用户滚动到
参考资料
演示
// When button#ADD is clicked...
$('#ADD').on('click', function(e) {
/* Random number to be interpolated in
|| Template Literal
*/
var ts = Math.round(Date.now() / Math.random() * 11);
/* Template Literal is a string with new
|| syntax and advanced methods and properties
*/
var str = `<fieldset id='setX${ts}' class='SET form-group'><div class="input-group"> <span class="input-group-addon"> <i class="glyphicon glyphicon-user"></i> </span> <input id="name-${ts}" type="text" class="form-control" name="name-${ts}" placeholder="Name"></div><div class="input-group"> <span class="input-group-addon"><i class="glyphicon glyphicon-envelope"></i> </span><input id="mail-${ts}" type="email" class="form-control" name="mail-${ts}" placeholder="Email"><span class="input-group-addon"><i class="glyphicon glyphicon-phone"></i></span><input id="cell-${ts}" type="phone" class="form-control" name="cell-${ts}" placeholder="Phone"></div><div class="input-group pull-right"><div id='setC${ts}' class="btn-group"><button id='CFG${ts}' type="button" class="CFG btn btn-success"> <i class='glyphicon glyphicon-cog'></i> </button> <button id="DEL${ts} "type="button" class="DEL btn btn-danger"> <i class='glyphicon glyphicon-minus'></i> </button></div></div> <span class="input-group-addon" style="height:35px">${ts} <i class="glyphicon glyphicon-info-sign"></i></span><textarea id="info-${ts}" type="text" class="form-control" name="info-${ts}" placeholder="Info" cols='120' rows='4'></textarea></fieldset>`;
// Append TL to DOM (string gets parsed as HTML)
$('#setD').append(str);
// Register the new button.DEL to click event
$('.DEL').on('click', DEL);
});
/* This the callback function for button.DEL
|| click event
*/
function DEL(e) {
// Get the closest fieldset.SET and remove it
var parent = $(this).closest('.SET').remove();
}
// When form#frm0 is submitted show a#RSP
$('#frm0').on('submit', function() {
$('#RSP').show();
});
/* When a#RSP is clicked, scroll to
|| iframe#response.
|| iframe#response receives the server response
|| and displays it.
*/
$("#RSP").click(function() {
$('html, body').animate({
scrollTop: $("#response").offset().top
}, 1000);
});
#RSP {
display: none
}
-
<!DOCTYPE html>
<html lang="en">
<head>
<title>BS Form</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<main class="container">
<form id="frm0" action="https://httpbin.org/post" method='post' target='response'>
<div class="input-group pull-right">
<div id='setA' class="btn-group"> <button id='ADD' type="button" class="ADD btn btn-primary"> <i class='glyphicon glyphicon-plus'></i> </button> <button id='CFG' type="button" class="CFG btn btn-success"> <i class='glyphicon glyphicon-cog'></i> </button>
<button id='SUB' type="submit" class="SUB btn btn-warning"> <i class='glyphicon glyphicon-send'></i> </button>
</div>
</div>
<fieldset id='setB' class='form-group'>
<legend>Contact Form</legend>
<a href='#/' id='RSP' class='btn btn-link'>View Response</a>
</fieldset>
<fieldset id='setD' class="form-group"></fieldset>
</form>
<iframe srcdoc='<h1 style="text-align:center;font-family:Consolas">Server Response</h1>' src='about:blank' id='response' name='response' frameborder='1' width='99%' height='300'></iframe>
</main>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>