开发者

I want to subtract text value have class in jquery

开发者 https://www.devze.com 2023-02-15 13:36 出处:网络
<html xmlns=\"http://www.w3.org/1999/xhtml\"> <head> <title>Sum of all TextBox values using jQuery</title>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Sum of all TextBox values using jQuery</title>
    <script type="text/javascript"
    src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js">
    </script>
    <script type="text/javascript">
        $(function() {
            $("#addAll").click(function() {
                var add = 0;
                $(".amt").each(function() {
                    add -= Number($(this).val());
                });
                $("#para").text("Sum of all textboxes is : " + add);
            });
        });
    </script>
</head>
<body>
    <input id="Text1" class="amt" type="text" /><br />
    <input id="Text2" class="amt" type="text" /><br />
    <input id="Text3" class="amt" type="text" /><br />  
    <input id="addAll" type="button" value="Sum all Textboxes" /><br />
    <p id="para" />
</body>
</html>

but i couldn't get the actual result. please help 开发者_运维问答me


Try:

$(function() {
    $("#addAll").click(function() {
        var add = 0;
        $(".amt").each(function() {
            add += parseInt($(this).val() || 0, 10);
        });
        $("#para").text("Sum of all textboxes is : " + add);
    });
});

Using parseInt. Additionally, you should use += if you're trying to sum the values.

Here it is working: http://jsfiddle.net/S9H6A/


Update: If you're trying to subtract all values in the text boxes, then your problem is that you're initializing the total to 0. Try something like this instead (Also added code from @Praveen's answer which uses || 0 to default empty inputs to 0):

$(function() {
    $("#addAll").click(function() {
        var total;
        $(".amt").each(function() {
            if (typeof total === 'undefined') {
                total = parseInt($(this).val() || 0, 10);
            }
            else {
                total -= parseInt($(this).val() || 0, 10);
            }
        });
        $("#para").text("Sum of all textboxes is : " + total);
    });
});

Updated example: http://jsfiddle.net/S9H6A/4/


replace this add -= Number($(this).val()); with add -= parseInt($(this).val()|| 0,10);

0

精彩评论

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