Juned Ansari Juned Ansari - 1 month ago 6
jQuery Question

Find Total on Dynamic basis using jquery

I am generating dynamic text box and wanted to perform sum operation of all the textbox values but it doesnot works.

below is my code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<div id='dynamicdiv'>
Val1:<input type="text" class='kk' name="qty[]">
</div>
<input type="button" id='btnadd' name="" value="ADD">
<input type="hidden" id="hdntxt" value="1">
<p>
Total : <span id="total"></span>
</p>
<script type="text/javascript">
$("#btnadd").click(function () {
i=$('#hdntxt').val();
i++;
$("#dynamicdiv").append('<br>Val'+i+':<input type="text" class="kk" name="qty[]">');
$('#hdntxt').val(i);
});
var inputs = $('.kk');
$('.kk').on("blur","input",function(){
var total = 0;
$.each(inputs, function(input){
var num = parseInt(inputs[input].value,10);
total += (!isNaN(num))? num : 0;
});
$("#total").html(total);
})
</script>

Answer

You have to use event delegation technique to bind event listener to dynamically generated DOM element like:

$(document).on("blur", "input.kk", function() {

Also need to move var inputs = $('.kk'); within event handler code as follows:

$(document).ready(function() {
  $("#btnadd").click(function() {
    i = $('#hdntxt').val();
    i++;
    $("#dynamicdiv").append('<br>Val' + i + ':<input type="text" class="kk" name="qty[]">');
    $('#hdntxt').val(i);
  });

  $(document).on("blur", "input.kk", function() {
    var total = 0;
    var inputs = $('.kk');
    $.each(inputs, function(input) {
      var num = parseInt(inputs[input].value, 10);
      total += (!isNaN(num)) ? num : 0;
    });
    $("#total").html(total);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id='dynamicdiv'>
  Val1:
  <input type="text" class='kk' name="qty[]">
</div>
<input type="button" id='btnadd' name="" value="ADD">
<input type="hidden" id="hdntxt" value="1">
<p>
  Total : <span id="total"></span>
</p>

Comments