Search code examples
jqueryautocompleteclone

Trying to use jQuery, Clone and multiplication function


I have an issue enabling functions with jQuery AutoComplete and Clone that I’m hoping somebody can help me with. Sorry if this is a bit over-detailed!

I have a table which has title, description, qty, price and total in it. The user can use autocomplete on the product field to fetch the title’s description and price. At the same time, I have an ‘add row’ function using clone and I’m trying to use another function to multiply the qty and price if either are changed. So far, I have the following:

Code for adding new row to table:

var $table;
$(function() {
     $table=$('#invoiceitems'); 
     var $existRow=$table.find('tr').eq(1);
      bindAutoComplete($existRow);
});

function addRow(){
    var $row=$table.find('tr:last').clone();
    var $input=$row.find('input:first');
    $row.find('input').val("");
    $row.find('#product_description').val("");
    $table.append($row);
    bindAutoComplete($row);
    $input.focus();
}

Code for AutoComplete:

function bindAutoComplete($row){
    $row.find(".product_title").autocomplete(products, {
        width: 380,
        matchContains: "word",
        formatItem: function(row) {
            return row.title;
        }
    });
    $row.find('.product_title').result(function(event, data) {
        $row.closest('.product_description').val(data.description);
        $row.find('.product_price').val(data.price);
        $row.find('.qty').val("1");
    });
}

Code for multiplying price and qty:

$(document).ready(function() {    
$(".qty, .product_price").keyup(function() {
   var $row = $(this).closest("tr"),
       price = $row.find(".product_price").val();
           qty = $row.find(".qty").val();
    $row.find(".line_total").text(qty * price);
});

At the moment, the AutoComplete and clone work fine however the multiplication for the qty and price only works on the first row and now on any new rows that are added. If I replace clone(); with clone(true); then the multiplication works however the AutoComplete does’t work properly as it updates the price on all previous rows when you use it.

I am not very good with JS and jQuery so I am hoping this is a simple mistake to correct?

Many thanks!


Solution

  • The problem is that clone(true) means that the data and event will also be clone.

    I would suggest that use clone() method and make the event like this

    for jQuery 1.7 and above.

    $(document).ready(function() {    
       $('table#invoiceitems').on('keyup', ".qty, .product_price", function() {
           var $row = $(this).closest("tr"),
           price = $row.find(".product_price").val();
           qty = $row.find(".qty").val();
           $row.find(".line_total").text(qty * price);
       }
    });
    

    for older versions u can use live().

    This method will be called for each new row which will be added to the table later on.