Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add input fields on button click

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">

its adding input fields one time and on second click its not adding anything and remove button is not working

like image 768
vivek modi Avatar asked Jun 07 '18 17:06

vivek modi


1 Answers

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">
like image 167
Zakaria Acharki Avatar answered Sep 28 '22 17:09

Zakaria Acharki