Question

I'm going to sum the values from different types of form elements. Drop down and input. The process is going well but I'm stuck at the total is not automate update after I change an option.

Here is my code:

<form>
        <label>cost: <input type="text" name="cost_1" size="5" class="summable"/></label>
        <label>qty: <input type="text" name="cost_1_qty" size="2"/></label><br/>

        <label>cost: <input type="text" name="cost_2" size="5" class="summable"/></label>
        <label>qty:     <select name="cost_2_qty">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    </select></label><br/>

        <label>cost: <input type="text" name="cost_3" size="5" class="summable"/></label>
        <label>qty: <input type="text" name="cost_3_qty" size="2"/></label><br/>

        <strong id="summation"></strong><br/>
    </form>
    <script type="text/javascript">

        function doTotal() {
            var total = 0.0;

            $(".summable").each(function (idx, element) {
                $this = $(this);

                var cost = parseFloat($this.val());
                var qty_selector = '[name=' + $this.attr('name') + '_qty' + ']'; // eg: [name=cost_3_qty]
                var qty = parseFloat($(qty_selector).val());
                if (cost && qty)
                    total += cost * qty ;
            });

            $("#summation").html(total.toFixed(2));
        }

        $(document).ready(function() {
            $("input[type=text]").blur(function (e) {
                doTotal();
            })
        });         
    </script>

Live version here: http://jsfiddle.net/hWcMv/

I need a total value to be calculated right after an option is selected. Please suggest.

Was it helpful?

Solution

    $(document).ready(function() {
        $('[name*="cost"]').change(function () {
            doTotal();
        })
    });​

http://jsfiddle.net/hWcMv/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top