How to add input fields on button click
Check the snippet, hope this is what you are looking for :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);
}
}
<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">
$('.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">
Working fiddle.
You have to use .append()
instead of .html()
when appending elements :
$('#new_chq').append(new_input);
It will be better to attach the event in your JS code like :
$('.add').on('click', add);
$('.remove').on('click', remove);
NOTE 1: Don't forget to increment the counter #total_chq
:
$('#total_chq').val(new_chq_no);
NOTE 2: You've to use .remove()
if you want to remove the element.
$('.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">