0

i have created some dynamic elements using jquery and add a dropdownlist using ajax inside dynamic elements ,The problem is when i select a option from a dropdownlist,then upcoming ajax data are override the all other dynamic elements data. See the picture

now i want to bind data every dynamic elements data separately in jquery.

  $(document).ready(function() {
  var html = $("#dsp > .row:first").first().html();
  var maxrows = 5;
  var x = 1;
  $("#addrow").click(function() {
    if (x <= maxrows) {
      $('#dsp').append(html);
      x++;
    }
  });

  $("#rmvrow").click(function() {
    $('#dsp').children().last().remove();
  });
  
    $('#dsp').on('change','.p_name',function(){
      var pid=$(this).val();
      var parent=$('#dsp');
      
      //alert(pid);
      $.ajax({
        url:"{{route('getinfo')}}",
        method:'post',
        data:{id:pid,'_token':"{{csrf_token()}}"},
        success:function(response) {  
            console.log(parent.find('.p_code').val(response.code));
  
        }
      });

    });
});


  
           <div id="dsp">
  <div class="row">
    <div class="col-md-2">
      <select name="p_name[]" class="form-control p_name">
      <option value="">-Select Product-</option>
      @foreach($products as $product)
      <option value="{{$product->product_id}}">{{$product->name}}</option>
      @endforeach
    </select>
    </div>
    <div class="col-md-2">
      <input type="text" name="p_code[]" class="form-control p_code">
    </div>
    <div class="col-md-2">
      <input type="text" name="unit_pctn[]" class="form-control unit_pctn" readonly="">
    </div>
    <div class="col-md-2">
      <input type="text" name="u_price[]" class="form-control u_price" readonly="">
    </div>
    <div class="col-md-1">
      <input type="text" name="ctn[]" class="form-control ctn">
    </div>
    <div class="col-md-1">
      <input type="text" name="pcs[]" class="form-control pcs">
    </div>
    <div class="col-md-2">
      <input type="text" name="t_amt[]" class="form-control t_amt">
    </div>

  </div><br>
</div>
Majeed
  • 149
  • 1
  • 3
  • 16

3 Answers3

0

Keep giving dynamic id for each of your rows and use that to add listeners.

On every add row call a funtion that does

function addrow(rownumber) {
    document.getElementById('dsp' + rownumber).addEventListener('click', function(event) {
        // do some action
    });
}
Gaudam Thiyagarajan
  • 1,022
  • 9
  • 24
  • He's already using jQuery delegation, why should he change to this style? – Barmar Nov 16 '17 at 21:13
  • It doesn't matter if it's Jquery or javascript. He can still add listener dynamically both ways. I just gave one possible solution. I guess his question was " How to bind event for dynamically created elements in JQuery " – Gaudam Thiyagarajan Nov 16 '17 at 21:24
  • Did you read the question and understand the problem he's having? How does your answer solve the problem that when he does the AJAX call it fills in the response in all the rows? – Barmar Nov 16 '17 at 21:26
0

Your code for delegating event binding is fine. The problem is that your second success function doesn't put the response in the current row, it fills in all .u_price fields. Change that to:

parent.find(".u_price").val(response.client_price);

When you add a new row, it needs to be inside its own <div class="row">, so that $(this).closest(".row") will select the correct row. You currently just have one class="row" and it's the #dsp DIV that contains all the rows. Each row needs to be a child of #dsp.

$(document).ready(function() {
  var html = $("#dsp > row:first").first().html();
  var maxrows = 5;
  var x = 1;
  $("#addrow").click(function() {
    if (x <= maxrows) {
      $('#dsp').append(html);
      x++;
    }
  });

  $("#rmvrow").click(function() {
    $('#dsp').children().last().remove();
  });
});
<div id="dsp">
  <div class="row">
    <div class="col-md-2">
      <select name="p_name[]" class="form-control p_name">
      <option value="">-Select Product-</option>
      @foreach($products as $product)
      <option value="{{$product->product_id}}">{{$product->name}}</option>
      @endforeach
    </select>
    </div>
    <div class="col-md-2">
      <input type="text" name="p_code[]" class="form-control p_code">
    </div>
    <div class="col-md-2">
      <input type="text" name="unit_pctn[]" class="form-control unit_pctn" readonly="">
    </div>
    <div class="col-md-2">
      <input type="text" name="u_price[]" class="form-control u_price" readonly="">
    </div>
    <div class="col-md-1">
      <input type="text" name="ctn[]" class="form-control ctn">
    </div>
    <div class="col-md-1">
      <input type="text" name="pcs[]" class="form-control pcs">
    </div>
    <div class="col-md-2">
      <input type="text" name="t_amt[]" class="form-control t_amt">
    </div>

  </div>
</div>
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • it's show the product code, but i can't bind it separately pcode field. – Majeed Nov 17 '17 at 19:50
  • I'm not sure what you mean by "bind it separately pcode field". – Barmar Nov 17 '17 at 20:29
  • Does it show the `client_price`? If not, there's a problem with your `getprice` API, it's not returning the desired information. – Barmar Nov 17 '17 at 20:30
  • when i select product name from dropdown list , it's fetch the product code by an ajax request.problem is i cannot assign product code for separately because last selected product code override the other field product code. please see this picture: https://i.imgur.com/9DXq0T2.png – Majeed Nov 17 '17 at 20:45
  • My answer only fixes the problem with the product price. It looks like you're already doing it correctly for `.p_code` and `.unit_pctn`. – Barmar Nov 17 '17 at 20:48
  • Do you have multiple `
    `? IDs need to be unique.
    – Barmar Nov 17 '17 at 20:49
  • no, there have only id dsp. i'm try this line after ajax success: console.log(parent.find('#p_code')); in console show this message: [prevObject: m.fn.init(11), context: document, selector: ".form-control #p_code"] – Majeed Nov 17 '17 at 20:56
  • Your image shows two rows of input fields. Aren't they both `
    `? If not, what does the second row look like?
    – Barmar Nov 17 '17 at 20:58
  • It should be `parent.find(".p_code")`. You need to search for a class, not an ID. – Barmar Nov 17 '17 at 20:59
  • You also shouldn't repeat `id="p_code"` in each row. – Barmar Nov 17 '17 at 21:00
  • now i'm try this code, var parent=$('#dsp'); after ajax success: console.log(parent.find('.p_code')); now show message in console: [input.form-control.p_code, prevObject: m.fn.init(1), context: document, selector: "#dsp .p_code"] – Majeed Nov 17 '17 at 21:13
  • Could you edit the question and show what the HTML looks like for two rows? – Barmar Nov 17 '17 at 21:14
  • after first row then every row append from this variable: var html='
    ';
    – Majeed Nov 17 '17 at 21:15
  • still overriding happen, i update my question please see. – Majeed Nov 18 '17 at 06:21
  • Don't remove the original code from the question. How will anyone understand what my answer was fixxing? – Barmar Nov 18 '17 at 06:55
0

Try this way.bind data working this way and calcuate total also work.

    $(document).ready(function(){
    $('#dsp').on('change','.p_name',function(){
      var pid=$(this).val();
      var parent= $(this).closest('.row');
      //alert(pid);
      $.ajax({
        url:"{{route('getinfo')}}",
        method:'post',
        data:{id:pid,'_token':"{{csrf_token()}}"},
        success:function(response) {   

          //alert(response.code);
          parent.find('.p_code').val(response.code);
          parent.find('.unit_pctn').val(response.pcs_per_ctn);
        }
      });

        $.ajax({
        url:"{{route('getprice')}}",
        method:'post',
        data:{id:pid,'_token':"{{csrf_token()}}"},
        success:function(response) {
          //alert(response.code);

          parent.find('.u_price').val(response.client_price);

        }
      });



    });

    //calculation here

    $('#dsp').on('input','.ctn',function(){
         var cal=$(this).val();
         var gparent=$(this).closest('.row');
         var unitp=gparent.find('.u_price').val();
         var unitpctn=gparent.find('.unit_pctn').val();
         var pcs=gparent.find('.pcs').val();
        //alert(pcs);
        var total=(((parseInt(unitpctn)*parseInt(cal)) + parseInt(pcs))*parseInt(unitp));

           gparent.find('.t_amt').val(total);

           //grand total
           var gtotal=0;
           var gtotal=parseInt(gtotal)+parseInt(total)
           //alert(gtotal);
           $('#tot').val(gtotal);


    });

     $('#dsp').on('input','.pcs',function(){
         var pcs=$(this).val();
         var gparent=$(this).closest('.row');
         var unitp=gparent.find('.u_price').val();
         var unitpctn=gparent.find('.unit_pctn').val();
         var ctn=gparent.find('.ctn').val();
        //alert(pcs);
        var total=(((parseInt(unitpctn)*parseInt(ctn)) + parseInt(pcs))*parseInt(unitp));

           gparent.find('.t_amt').val(total);

           //grand total

           var gtotal=0;
           $('.t_amt').each(function(){ gtotal += parseFloat($(this).val()) || 0; $('#tot').val(gtotal); }); 
         });

  });
Apurva Kolapkar
  • 1,270
  • 2
  • 16
  • 32
Gabrielle-M
  • 1,037
  • 4
  • 17
  • 39