开发者

change div content based on three for elements

开发者 https://www.devze.com 2023-01-22 05:10 出处:网络
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:

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!


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);

});
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号