-3

As per my screenshot here: https://drive.google.com/file/d/1N3ozAMXjbpyjmMNIE7xk6kOvZRB58Koy/view

Muy first row of extras items and options are working fine, I created these functions with a PHP variable/counter.

So, I intend to do the to do the same with Jquery and a counter when I clone new rows of extras and options as show with the red arrows, but does not work.

Please, see the file running here: https://quotations.casalindacity.com/newquotation.php

//START CACULATION AUTOMATIC FOR OPCIONS ITEMS WITH JQUERY
     for (var c = 1; c < opcionescant; c++) {
        alert(c);
        $('#priceoptc'+c).keyup(function () {

            //calculate the total amount of this option
            var amountextra = 0;
            amountextra =((Number($('#priceoptc'+c).val()))*(Number($('#qtyoptc'+c).val())));
            $('#totaloptc'+c).val(amountextra);
        });

        $('#qtyoptc'+c).keyup(function () {

            //calculate the total amount of this option
            var amountextra = 0;
            amountextra =((Number($('#priceoptc'+c).val()))*(Number($('#qtyoptc'+c).val())));
            $('#totaloptc'+c).val(amountextra);
        });
     }

    //END CACULATION AUTOMATIC FOR OPCIONS ITEMS WITH JQUERY

I have tried this:

$("#addRow10").click(function(){
opcionescant++;
//$("#options").clone().appendTo("#tableqtn");
var optrow = $("#options").clone(true,true);
//fixIds(optrow, opcionescant);//add this counter to the current id as a string
fixIds2(optrow, opcionescant);//add this counter to the current id and replace with current number
optrow.appendTo("#tableqtn");
//alert(opcionescant);

$('#priceoptc'+opcionescant).keyup(function () {

        //calculate the total amount of this option
        var amountextra = 0;
        amountextra =((Number($('#priceoptc'+opcionescant).val()))*(Number($('#qtyoptc'+opcionescant).val())));
        $('#totaloptc'+opcionescant).val(amountextra);
    });

    $('#qtyoptc'+opcionescant).keyup(function () {

        //calculate the total amount of this option
        var amountextra = 0;
        amountextra =((Number($('#priceoptc'+opcionescant).val()))*(Number($('#qtyoptc'+opcionescant).val())));
        $('#totaloptc'+opcionescant).val(amountextra);
    });

});

And work but only in the current cloned row, so when a new row is cloned the previous one does not work.

  • Already pointed out that the `for` loop you are using won't work the way it is written when you asked the same question here https://stackoverflow.com/questions/57452083/function-in-jquery-no-working-as-in-the-first-id-when-i-run-a-for-on-each-cloned – charlietfl Aug 11 '19 at 21:32
  • Possible duplicate of [Function in Jquery no working as in the first id when I run a for on each cloned rows of a table with ids changed](https://stackoverflow.com/questions/57452083/function-in-jquery-no-working-as-in-the-first-id-when-i-run-a-for-on-each-cloned) – David784 Aug 11 '19 at 21:47
  • I have done you you stated: https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example but still the problem pesist. – joseluis Diaz Aug 12 '19 at 00:35
  • var funcs = []; function createfunc(i) { return function() { $('#priceoptc'+i).keyup(function () { var amountextra = 0; amountextra =((Number($('#priceoptc'+i).val()))*(Number($('#qtyoptc'+i).val()))); $('#totaloptc'+i).val(amountextra); }); $('#qtyoptc'+i).keyup(function () { var amountextra = 0; amountextra =((Number($('#priceoptc'+i).val()))*(Number($('#qtyoptc'+i).val()))); $('#totaloptc'+i).val(amountextra); }); }; } – joseluis Diaz Aug 12 '19 at 00:37
  • for (var i = 1; i <= opcionescant; i++) { funcs[i] = createfunc(i); } for (var j = 1; j < opcionescant; j++) { funcs[j](); } – joseluis Diaz Aug 12 '19 at 00:38
  • As I asked in the other question. Please click [edit](https://stackoverflow.com/posts/57453448/edit), then click on the icon that looks like this: `[<>]` - add HTML and relevant CSS. Do NOT add code in comments. – mplungjan Aug 12 '19 at 05:30
  • You do NOT need to give the fields any IDs Just give them a relevant class and you can use `$(this).closest("tr").find(".price").val()` to get the price for example. Also why not use jQuery all the way. Your code is an unmaintainable mix of DOM and jQuery – mplungjan Aug 12 '19 at 05:47

2 Answers2

1

Assuming both the elements are placed on the same hierarchy in HTML. Add the following class to #priceoptc element: priceElement, for #qtyoptc element have qtyElement and for #totaloptc element use totalElement class.

Then use the following code:

$('#priceoptc'+opcionescant).keyup(function (event) {

    //calculate the total amount of this option
    var amountextra = 0;
    amountextra =((Number($(event.target).val()))*(Number($(event.target).siblings('.qtyElement').val())));
    $(event.target).siblings('.totalElement').val(amountextra);
});

Please take into account the assumption of HTML structure if yours is more complicated than the one i have assumed then please do mention the HTML Structure.

Arpit Bansal
  • 493
  • 1
  • 4
  • 15
0

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script> 

<script type="text/javascript">

var opcionescant=1;
var extrascant=1;

$("#addRow10").click(function(){
 opcionescant++;
 var optrow = $("#options").clone(true,true);
 fixIds2(optrow, opcionescant);//add this counter to the current id and replace with current number
 
 optrow.appendTo("#tableqtn");
 
 createopcion(opcionescant);
});

$("#clonarextra").click(function(){
 extrascant++;
 var extrow = $("#trextra").clone(true,true);
 fixIds2(extrow, extrascant);//add this counter to the current id and replace with current number
 if (extrascant==2){
  extrow.insertAfter("#trextra");
 }else{
  extrow.insertAfter("#trextra"+(extrascant-1));
 }
 createextra(extrascant);
 
});

function createopcion(i) {
    $('#priceoptc'+i).keyup(function () {
   //calculate the total amount of this option
   var amountextra = 0;
   amountextra =((Number($('#priceoptc'+i).val()))*(Number($('#qtyoptc'+i).val())));
   $('#totaloptc'+i).val(Math.round(amountextra));
  });
  
  $('#qtyoptc'+i).keyup(function () {
   //calculate the total amount of this option
   var amountextra = 0;
   amountextra =((Number($('#priceoptc'+i).val()))*(Number($('#qtyoptc'+i).val())));
   $('#totaloptc'+i).val(Math.round(amountextra));
  });
}

function createextra(i) {
  $('#ext'+i).change(function () {
   //==========get villa price------------------
   var extraid = this.value;
   $.ajax({
    type: 'POST',
    url: 'ajax/extradetails.php',
    data: { extraselected: extraid },
    dataType: 'json',
    cache: false,
    success: function(response) {
     $('#priceext'+i).val(response['sales']);
     
     switch(response['unit']) {
       case 'm2':
      var unithtml='m<sup>2</sup>';
      // code block
      break;
       case 'lm':
      var unithtml='lm';
      // code block
      break;
     case 'gl':
      var unithtml='gls';
      // code block
      break;
     case 'm3':
      var unithtml='m<sup>3</sup>';
      // code block
      break;
     case 'set':
      var unithtml='set';
      // code block
      break;
     case 'pc':
      var unithtml='pc.';
      // code block
      break;
       default:
      var unithtml='m<sup>2</sup>';
      // code block
     }
    $("#funit"+i).html(unithtml); 
    $("#tunit"+i).html(unithtml);
    }
   });
   //get the qtn of this extra
   var qtnextra = 0;
   qtnextra =Number($('#toext'+i).val())-Number($('#fromext'+i).val());
   $('#qtyext'+i).val(qtnextra.toFixed(2));
   //calculate the total amount of this extra
   var amountextra = 0;
   amountextra =((Number($('#qtyext'+i).val()))*(Number($('#priceext'+i).val())));
   $('#totalext'+i).val(Math.round(amountextra));
   //get total amount including extras
    var sum = 0;
   $('.price').each(function() {
    sum += Number($(this).val());
   });
   $('#totalPrice').val(Math.round(sum));
   //get the total including discount
   var neto = 0;
   neto =Number($('#totalPrice').val())-Number($('.discount').val());
   $('#totalNet').val(Math.round(neto));
  });
 
  //update from and to when numbers change
  $('#fromext'+i).keyup(function () {
   //get the qtn of this extra
   var qtnextra = 0;
   qtnextra =Number($('#toext'+i).val())-Number($('#fromext'+i).val());
   $('#qtyext'+i).val(qtnextra.toFixed(2));
   //calculate the total amount of this extra
   var amountextra = 0;
   amountextra =((Number($('#qtyext'+i).val()))*(Number($('#priceext'+i).val())));
   $('#totalext'+i).val(Math.round(amountextra));
   //get total amount including extras
    var sum = 0;
   $('.price').each(function() {
    sum += Number($(this).val());
   });
   $('#totalPrice').val(Math.round(sum));
   //get the total including discount
   var neto = 0;
   neto =Number($('#totalPrice').val())-Number($('.discount').val());
   $('#totalNet').val(Math.round(neto));
  });
 
  $('#toext'+i).keyup(function () {
   //get the qtn of this extra
   var qtnextra = 0;
   qtnextra =Number($('#toext'+i).val())-Number($('#fromext'+i).val());
   $('#qtyext'+i).val(qtnextra.toFixed(2));
   //calculate the total amount of this extra
   var amountextra = 0;
   amountextra =((Number($('#qtyext'+i).val()))*(Number($('#priceext'+i).val())));
   $('#totalext'+i).val(Math.round(amountextra));
   //get total amount including extras
    var sum = 0;
   $('.price').each(function() {
    sum += Number($(this).val());
   });
   $('#totalPrice').val(Math.round(sum));
   //get the total including discount
   var neto = 0;
   neto =Number($('#totalPrice').val())-Number($('.discount').val());
   $('#totalNet').val(Math.round(neto));
  });
}



//If elem is the parent of your cloned structure and cntr is the counter you said you were maintaining, you can fix all ids in that cloned structure like this:
function fixIds(elem, cntr) {
    $(elem).find("[id]").add(elem).each(function() {
        this.id = this.id + cntr;
    })
}
//If the ids might already have a cloned number at the end and you want to replace that number, you can do so like this:
function fixIds2(elem, cntr) {
    $(elem).find("[id]").add(elem).each(function() {
        this.id = this.id.replace(/\d+$/, "") + cntr;
    })
}

     // DELETE TABLE ROW.
    function removeRow(oButton) {
        var empTab = document.getElementById('tableqtn');
        empTab.deleteRow(oButton.parentNode.parentNode.rowIndex);       // BUTTON -> TD -> TR.
    }
 
 function r2dec(i) {
  
  return Number(i.toFixed(2));
 }

 function rNOde(i) {
  
  return Number(Math.round(i));
 }

 $('#ext1').change(function () {
  
  
  
  //==========get villa price------------------
  var extraid = this.value;
  $.ajax({
   type: 'POST',
   url: 'ajax/extradetails.php',
   data: { extraselected: extraid },
   dataType: 'json',
   cache: false,
   success: function(response) {
    $('#priceext1').val(response['sales']);
    $('#unitext1 option[value="'+response['unit']+'"]');
    
    switch(response['unit']) {
       case 'm2':
      var unithtml='m<sup>2</sup>';
      // code block
      break;
       case 'lm':
      var unithtml='lm';
      // code block
      break;
     case 'gl':
      var unithtml='gls';
      // code block
      break;
     case 'm3':
      var unithtml='m<sup>3</sup>';
      // code block
      break;
     case 'set':
      var unithtml='set';
      // code block
      break;
     case 'pc':
      var unithtml='pc.';
      // code block
      break;
       default:
      var unithtml='m<sup>2</sup>';
      // code block
     }
    $("#funit1").html(unithtml); 
    $("#tunit1").html(unithtml);
   }
  });
  
  //get the qtn of this extra
  var qtnextra = 0;
  qtnextra =$('#toext1').val()-$('#fromext1').val();
  $('#qtyext1').val(qtnextra.toFixed(2));
  //calculate the total amount of this extra
  var amountextra = 0;
  amountextra =((Number($('#qtyext1').val()))*(Number($('#priceext1').val())));
  $('#totalext1').val(Math.round(amountextra));
  
  //get total amount including extras
   var sum = 0;
  $('.price').each(function() {
   sum += Number($(this).val());
  });
  $('#totalPrice').val(Math.round(sum));
  
  //get the total including discount
  var neto = 0;
  //neto =Number($('#totalPrice').val())-Number($('.discount').val());
  neto =Number($('#totalPrice').val())-Number($('.discount').val());
  $('#totalNet').val(Math.round(neto));
  
 });
 
 //update from and to when numbers change
 $('#fromext1').keyup(function () {
  //get the qtn of this extra
  var qtnextra = 0;
  qtnextra =$('#toext1').val()-$('#fromext1').val();
  $('#qtyext1').val(qtnextra.toFixed(2));
  //calculate the total amount of this extra
  var amountextra = 0;
  amountextra =((Number($('#qtyext1').val()))*(Number($('#priceext1').val())));
  $('#totalext1').val(Math.round(amountextra));
  
  //get total amount including extras
   var sum = 0;
  $('.price').each(function() {
   sum += Number($(this).val());
  });
  $('#totalPrice').val(Math.round(sum));
  
  //get the total including discount
  var neto = 0;
  neto =Number($('#totalPrice').val())-Number($('.discount').val());
  $('#totalNet').val(Math.round(neto));
 });
 
 $('#toext1').keyup(function () {
  //get the qtn of this extra
  var qtnextra = 0;
  qtnextra =$('#toext1').val()-$('#fromext1').val();
  $('#qtyext1').val(qtnextra.toFixed(2));
  //calculate the total amount of this extra
  var amountextra = 0;
  amountextra =((Number($('#qtyext1').val()))*(Number($('#priceext1').val())));
  $('#totalext1').val(Math.round(amountextra));
  
  //get total amount including extras
   var sum = 0;
  $('.price').each(function() {
   sum += Number($(this).val());
  });
  $('#totalPrice').val(Math.round(sum));
  
  //get the total including discount
  var neto = 0;
  neto =Number($('#totalPrice').val())-Number($('.discount').val());
  $('#totalNet').val(Math.round(neto));
 });

 $('#priceoptc1').keyup(function () {
  
  //calculate the total amount of this option
  var amountextra = 0;
  amountextra =((Number($('#priceoptc1').val()))*(Number($('#qtyoptc1').val())));
  $('#totaloptc1').val(Math.round(amountextra));
 });
 
 $('#qtyoptc1').keyup(function () {
  
  //calculate the total amount of this option
  var amountextra = 0;
  amountextra =((Number($('#priceoptc1').val()))*(Number($('#qtyoptc1').val())));
  $('#totaloptc1').val(Math.round(amountextra));
 });
</script>

This was my solution:

var opcionescant=1;
var extrascant=1;

$("#addRow10").click(function(){
    opcionescant++;
    var optrow = $("#options").clone(true,true);
    fixIds2(optrow, opcionescant);//add this counter to the current id and replace with current number

    optrow.appendTo("#tableqtn");

    createopcion(opcionescant);
});

$("#clonarextra").click(function(){
    extrascant++;
    var extrow = $("#trextra").clone(true,true);
    fixIds2(extrow, extrascant);
    if (extrascant==2){
        extrow.insertAfter("#trextra");
    }else{
        extrow.insertAfter("#trextra"+(extrascant-1));
    }
    createextra(extrascant);

});