0

I want to calculate using jQuery keyup function.

Total Price = Quality x Unit Cost Price

Total Price = Quality x Unit Selling Price

jQuery:

$('input').keyup(function(){
        //calculate
    });

The problem is: when I click add price button, the new rows are added. How to call the new row id?

price

HTML:

<div class="price_table">
        <div class="row">
            <div class="span5 offset1"><h1>Price Breakdown<h1></div>
            <div class="span4 offset1"><input type="button" id="add_price" class="btn btn-primary" value="Add Price" style="float:right;margin:30px 0px 5px 0px;"/></div>
        </div>
        <div class="row">
            <div class="span10 offset1">
        <table class="addcost_table table tablesorter">
            <thead>
                <tr class="header_row">
                    <th>Item Group</th>
                    <th>Name</th>
                    <th>Code</th>
                    <th>Quantity</th>
                    <th class="cost_price">Unit Cost Price</th>
                    <th class="selling_price">Unit Selling Price</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                   <td><?= form_input('items[0][sub_header]', 'Hotel') ?></td>
                   <td><?= form_input('items[0][name]', 'Twin Room') ?></td>
                   <td><?= form_input('items[0][price_type]', 'TWN') ?></td>
                   <td><?= form_input('items[0][quantity]', '5') ?> </td>
                   <td class="cost_price"><?= form_input('items[0][cost]', '100') ?> </td>
                   <td class="selling_price"><?= form_input('items[0][price]', '120') ?> </td>
                </tr>
                <tr>
                   <td><?= form_input('items[1][sub_header]', 'Hotel') ?></td>
                   <td><?= form_input('items[1][name]', 'Single Room') ?></td>
                   <td><?= form_input('items[1][price_type]', 'SGL') ?></td>
                   <td><?= form_input('items[1][quantity]', '1') ?> </td>
                   <td class="cost_price"><?= form_input('items[1][cost]', '80') ?> </td>
                   <td class="selling_price"><?= form_input('items[1][price]', '100') ?> </td>
                </tr>
                <tr>
                   <td><?= form_input('items[2][sub_header]', 'Meals') ?></td>
                   <td><?= form_input('items[2][name]', 'Buffet Breakfast') ?></td>
                   <td><?= form_input('items[2][price_type]', 'BRE') ?></td>
                   <td><?= form_input('items[2][quantity]', '2') ?> </td>
                   <td class="cost_price"><?= form_input('items[2][cost]', '10') ?> </td>
                   <td class="selling_price"><?= form_input('items[2][price]', '10') ?> </td>
                </tr>
                <tr>
                   <td  colspan="4" style="text-align:right;margin-right:10px;"><b><span style="margin-right:20px;">Total Price X Qty</span></b></td>
                   <td class="cost_price"><?= form_input('items[3][cost]', '600') ?></td>
                   <td class="selling_price"><?= form_input('items[3][cost]', '500') ?></td>

                </tr>
            </tbody>
        </table>
        </div>
        </div>

        <div class="row">
            <div class="span11 offset1">
             <?= form_submit(array('class' => 'btn btn-primary'), 'Submit') ?>
            </div>  
        </div>
    </div>

Thanks a lot my friends.

7
  • what happen if you click add price? new field come up? Commented Apr 2, 2014 at 7:23
  • 3
    It's not clear to me What are you really trying to achieve and what is the real problem. Commented Apr 2, 2014 at 7:24
  • can you please provide the more details about your problem. Commented Apr 2, 2014 at 7:26
  • Total price from javascript browser side calculation can not be trusted on server side. Commented Apr 2, 2014 at 7:26
  • try to add class to field that you need to calculate. let say class="ABC" then in you jquery $('.ABC').keyup(function(){ //calculate }); Commented Apr 2, 2014 at 7:27

4 Answers 4

1

Working fiddle:

http://jsfiddle.net/vYbb2/

I've tried to let the table as you stated...

$('input').keyup( function(self) {
  var buyCostAcc = 0;
  var sellCostAcc = 0;
  $($($($(this).parent().parent().parent()).children()).slice(1, -1)).each(function(self){
    var quantity = $($(this).children()[3]).children().val();
    var buyCost = $($(this).children()[4]).children().val();
    var sellCost = $($(this).children()[5]).children().val();
    buyCostAcc += quantity * buyCost;
    sellCostAcc += quantity * sellCost;
  });
  $($($($($($(this).parent().parent().parent()).children()).slice(-1)).children()[2]).children()).val(buyCostAcc);
  $($($($($($(this).parent().parent().parent()).children()).slice(-1)).children()[3]).children()).val(sellCostAcc);
});

You can make-up a little bit the js code by assigning this large parent().parent... to variables. You cannot get all the work done :)

UPDATE

Here: http://jsfiddle.net/AteQ2/

Note that I've removed the thead and tbody tags.

The trick here is to go up from the input DOM node that causes the key-up event until reach to the table node. Once you have found the table, you can play with children to get each row, and then do the same to get the cells (and the inputs inside the cells). The slice jQuery's method is pretty cool, you have a wide explanation here. JS console and debugger is very helpfull (almost mandatory) for this kind of DOM "tricks".

Sign up to request clarification or add additional context in comments.

2 Comments

As @Paul says, if this is going to be a real hotel booking service, I hope you have a check process from the server side, otherwise the client could stay in the hotel like forever with no cost :D
You code is pretty good bro.but i can't understand.can you show me with my code. concept is same but I don't know how to make it on my code Thanks a lot bro.
1
$(document).ready(function (){

    $('input').keyup(function(){
        //calculate
        var costpriceSum = 0;
        var selling_priceSum = 0;
        $.find(".cost_price").each(function (){
            costpriceSum += $(this).value;
        });
        $.find(".selling_price").each(function (){
            selling_priceSum += $(this).value;
        });

        //Set costpriceSum
        //Set selling_priceSum

    });

});

2 Comments

can you write me how to calculate this Total Price = Quality x Unit Cost Price Total Price = Quality x Unit Selling Price
I guess the html is php and I am no expert (i suck) at php. So perhaps my answer should be deleted and someone with more php-skills should take over. However I would tag the td's with classes and/ord ids and with that I would have the ability to summarize...
1

You might want to give each input element an own class so you can easily loop over it.

// Enclosed in an anonymous func, is for namespacing, global variables, performance etc.
// See: http://stackoverflow.com/questions/2421911/what-is-the-purpose-of-wrapping-whole-javascript-files-in-anonymous-functions-li
(function(window, document, $, undefined) {
    var totalSelling = calculateTotal('.selling_price_element');
    var totalCost = calculateTotal('.cost_price_element');

    function calculateTotal(element)
    {
        // Start at 0;
        var total = 0;

        // Loop over each element
        $(element).each(function() {

            var element = $(this),
                price = element.val(); // Get the value

            price = parseFloat(price); // Convert the input to a workable float.

            // You might want to do some rounding, validation etc.. here.

            total = total + price; 

        });

        // return the total, round to two decimals
        return total.toFixed(2);
    }
})(this, document, jQuery);

Comments

0

To register listeners to future elements (i.e. that will be created after you set the handler), use on() with second param as selector:

$(document).on('keyup', 'input', function(){
    //calculate
});

This says any time a keyup event happens, check if it was from input and if yes, then call my function.

2 Comments

This is an answer to what?
@adripanico: To original question which was just "I want to calculate something after keyup with code '$('input').keyup(function() {}) but it does not work for new rows'. There was no mentioning that he actually does not know how to do math in javascript...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.