views:

36

answers:

1

Hey guys, I'm new to jQuery/js and having a hard time figuring this out. There are two fields in a form of mine i want to do some calculations with, what i tried is this:

jQuery.fn.calculateit = function(){

    var one = $("#one").val();

    var two = $("#two").val();

    //total
    var total = one + two;
    $("#total").text(total);

};

The values "one" and "two" can change at any time, and every time that happens i want the total to change. So I wrote the method above, but I have no idea how to have it called any time something happens with the two fields.

Any ideas?

Maybe I'm on the wrong track, so any suggestions are welcome!

Thanks!

+2  A: 

Here you go:

$("#one, #two").change(function() {
    calculateit();
});

var calculateit = function() {

    var one = parseInt($("#one").val(), 10);
    var two = parseInt($("#two").val(), 10);

    //total
    var total = one + two;
    $("#total").text(total);

};

Or, if you prefer, you can add calculateit to jQuery.fn and call it with $.calculateit().

Or, more concisely:

$("#one, #two").change(function() {

    var one = parseInt($("#one").val(), 10);
    var two = parseInt($("#two").val(), 10);

    //total
    var total = one + two;
    $("#total").text(total);

});
Chetan
Or you could make it a little more concise with: `$('#one, #two').change(/*...*/);`
David Thomas
@David: Thanks, I have updated my answer.
Chetan
To be safe, I recommend calling `parseInt()` or `parseFloat` on the returned values before adding them together. Otherwise, you may be concatenating two strings instead of adding their numeric values.
Blackcoat
@Blackcoat: I have updated my answer with your suggestion.
Chetan
+1 - but, if you use parseInt, it's very important to include the radix of `10`. ==> `parseInt($("#one").val(), 10)` otherwise numbers that begin with a `0` will be assumed to be octal!
Peter Ajtai
@Peter: Updated my answer again.
Chetan
Thanks a lot! I'll try that
Sled
One more questions: How do I trigger the change event when #one and #two are sliders? It doesn't work the way described below, and I don't know how to call them 'together'..
Sled
@Sled: Looks like sliders also have the `change` function, but if they can't be called together, then just use the first block of code and call `calculateit` separately for each slider change.
Chetan
Did it that way, and it worked. Thanks again!
Sled