ypcryz
ypcryz

Reputation: 172

Javascript dynamically calculate many row use one function

I have code like this :

Qty: <input type="text" name="qty" id="qty" class="txt" value="" />

Price: <input type="text" name="price" id="price" class="txt" value="500" />

Total: <input type="text" name="total" id="total" class="txt" value="" />

Javascript:

$('#qty').keyup(function() {
     var quantity = $("#qty").val();
     var priceItem = $("#price").val();
     var total = quantity * priceItem ;
     $("#total").val(total);
});

It's just one row. How to make function can be use to all row?

Upvotes: 0

Views: 1010

Answers (2)

krishwader
krishwader

Reputation: 11381

Why not use classes? It'll give you more fine tuned control over your elements and heck, it makes coding easier :)

Manipulating ids through selectors degrades performance and makes code messy to maintain. What if you decide to add a - in between qty and 1 in qty1? You'd have to change that 30 times, assuming you have that qty field 30 times.

Here's how your markup would look like:

Qty:
<input type="text" name="qty" class="txt qty" value="" />
<br/>
Price:
<input type="text" name="price" class="txt price" value="500" />
<br/>
Total:
<input type="text" name="total" class="txt total" value="" />

Your JavaScript :

Then, in your keyup method:

$('.qty').keyup(function () {
    var sibs = $(this).siblings();
    var quantity = this.value;
    var priceItem = sibs.filter(".price").val();
    var total = quantity * priceItem;
    sibs.filter(".total").val(total);
});

Demo : http://jsfiddle.net/hungerpain/bCKxW/

Upvotes: 1

som
som

Reputation: 4656

If your input fields id is looking like qty_1, price_1 and total_1 then you can do this :

$('input[id^=qty]').keyup(function() {

        var quantity = $(this).val();
        var idAttr =   $(this).attr('id').split('_');
        var i = idAttr[1];
        var priceItem = $("#price_" + i).val();
        var total = quantity * priceItem ;
        $("#total_" + i).val(total);
});

Upvotes: 0

Related Questions