function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
var new_input = "<input type='text' id='new_" + new_chq_no + "'>";
$('#new_chq').html(new_input);
}
function remove() {
var last_chq_no = $('#total_chq').val();
if (last_chq_no > 1) {
$('#new_' + last_chq_no).append('');
$('#total_chq').val(last_chq_no - 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
<input type="hidden" value="1" id="total_chq">
它添加输入字段一次,第二次点击它不添加任何内容而删除按钮不起作用
答案 0 :(得分:2)
<强> Working fiddle 强>
添加元素时,您必须使用.append()
代替.html()
:
$('#new_chq').append(new_input);
最好在JS代码中附加事件,如:
$('.add').on('click', add);
$('.remove').on('click', remove);
注1:不要忘记增加计数器#total_chq
:
$('#total_chq').val(new_chq_no);
注2:如果要删除元素,则必须使用.remove()
。
$('.add').on('click', add);
$('.remove').on('click', remove);
function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
var new_input = "<input type='text' id='new_" + new_chq_no + "'>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no);
}
function remove() {
var last_chq_no = $('#total_chq').val();
if (last_chq_no > 1) {
$('#new_' + last_chq_no).remove();
$('#total_chq').val(last_chq_no - 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button class="add">Add</button>
<button class="remove">remove</button>
<div id="new_chq"></div>
<input type="hidden" value="1" id="total_chq">
答案 1 :(得分:0)
检查代码段,希望这就是您要找的内容:D
function add(){
var new_chq_no = parseInt($('#total_chq').val())+1;
var new_input="<input type='text' id='new_"+new_chq_no+"'>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no)
}
function remove(){
var last_chq_no = $('#total_chq').val();
if(last_chq_no>1){
$('#new_'+last_chq_no).remove();
$('#total_chq').val(last_chq_no-1);
}
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button onclick="add()">Add</button>
<button onclick="remove()">remove</button>
<div id="new_chq"></div>
<input type="hidden" value="1" id="total_chq">
&#13;
答案 2 :(得分:0)
$('.add').on('click', add);
$('.remove').on('click', remove);
function add() {
var new_chq_no = parseInt($('#total_chq').val()) + 1;
var new_input = "<input type='text' id='new_" + new_chq_no + "'>";
$('#new_chq').append(new_input);
$('#total_chq').val(new_chq_no);
}
function remove() {
var last_chq_no = $('#total_chq').val();
if (last_chq_no > 1) {
$('#new_' + last_chq_no).remove();
$('#total_chq').val(last_chq_no - 1);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<button class="add">Add</button>
<button class="remove">remove</button>
<div id="new_chq"></div>
<input type="hidden" value="1" id="total_chq">