我在下面的表单中创建了动态添加行。 +按钮工作得非常好,但是当我尝试从X按钮中移除行(动态添加)时,它无法删除行并返回" Uncaught TypeError"。这涉及javascript和jquery。
在您运行代码段时,请向下滚动以查看结果。
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr><td><input type="text" name="name[]" placeholder="Category" class="form-control name_list" /></td><td><input type="radio" name="inlineRadioOptions []" value="Yes  "> Yes   <label class="radio-inline"><input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="No"> No</label></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({//here you can send date to DB
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<div class="card-body">
<h5 class="card-text"><div style="text-align: left">Deliverables</div></h5>
<h6 class="card-subtitle mb-2 text-muted"><div style="text-align: left">Press + to add minors</div></h6>
<button id="add" class="btn add-more"type="button">+</button>
</div>
<div class="container">
<div class="row">
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<div class="controls" id="profs">
<form id="main_delivery" class="input-append">
<div id="field">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Category" class="form-control name_list" /></td>
<td><input type="radio" name="inlineRadioOptions []" value="Yes  "> Yes   <label class="radio-inline"><input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="No"> No</label></td>
</tr></table>
</div>
</form></div>
</div>
</div>
</div>
&#13;
答案 0 :(得分:1)
请尝试以下代码:
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Category" class="form-control name_list" /></td><td><input type="radio" name="inlineRadioOptions []" value="Yes  "> Yes   <label class="radio-inline"><input type="radio" name="inlineRadioOptions" id="inlineRadio1" value="No"> No</label></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$('#submit').click(function(){
$.ajax({//here you can send date to DB
url:"name.php",
method:"POST",
data:$('#add_name').serialize(),
success:function(data)
{
alert(data);
$('#add_name')[0].reset();
}
});
});
});
答案 1 :(得分:0)
.on()
比v1.4.1要晚得多。尝试更新为&gt; = v1.7或使用.delegate()
。无论哪种方式,您仍然需要将版本提升至至少v1.4.2,因为这是引入.delegate()
的版本。