views:

39

answers:

1

Hey everyone,

Simple question, but I can't figure it out.

What is the launcher syntax I need to perform the following function:

<input type="text" id="value1" />
<input type="text" id="value2" />
<input type="text" id="value3" />
<input type="text" id="total" />

I want to perform [(value1 * value2) + value3] and have the result rounded to two decimal places (forced, so even if the result is a round integer, it should append ".00") and displayed in total. And I need this to happen on a keyup action for any of the value fields.

Should be very straightforward, but I just can't figure it out.

Help please?

Thanks

+3  A: 
$(function() {
    var roundDecimals = 2;
    var pow = Math.pow(10, roundDecimals);

    $('input[id^=value]').keyup(function() {
        var value1 = parseFloat($('#value1').val());
        var value2 = parseFloat($('#value2').val());
        var value3 = parseFloat($('#value3').val());

        if (isNaN(value1) || isNaN(value2) || isNaN(value3)) {
            return;
        }

        var total = value1 * value2 + value3;
        total = Math.round(total * pow) / pow;
        $('#total').val(total.toFixed(roundDecimals));
    });
});
Darin Dimitrov
Elegant, with error validation. Thank you! My question initially was on how to use the jQuery Calculate plugin to do it, but I think this way incurs far less overhead than the plugin! :)
RCd
Oops, I didn't even know such a plugin existed :-)
Darin Dimitrov