0

I have the following table:

<table>
    <thead>
        <tr>
            <th></th>
            <th>Female</th>
            <th>Male</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Rising 1</td>
            <td>
                <input id="firstinput" />
            </td>
            <td>
                <input id="secondinput" />
            </td>
        </tr>
        <tr>
            <td>Rising 2</td>
            <td>
                <input id="thirdinput" />
            </td>
            <td>
                <input id="fourthinput" />
            </td>
        </tr>
        <tr>
            <td>2+</td>
            <td>
                <input id="fifthinput" />
            </td>
            <td>
                <input id="sixthinput" />
            </td>
        </tr>
    </tbody>
</table>

I'm wanting to add all the values in these inputs together and display their value:

$(document).ready(function () {

        $('#mybutton').click(function () {

            alert(parseInt($('#firstinput').val()) +
                parseInt($('#secondinput').val()) +
                parseInt($('#thirdinput).val()) +
                parseInt($('#fourthinput').val()) +
                parseInt($('#fifthinput).val()) +
                parseInt($('#sixthinput').val()));
        });
});

Well this only works when all the values are present in the table. If one is empty end up with NaN.

How do you get around this?

Also am I approaching this completely wrong? Is there a better way to achieve this?

7 Answers 7

7

You could simply turn it into an or clause:

var total = 0;

$('input').each(function() {
    total += (+$(this).val() || 0);
});

alert(total);

Remember: +$(this).val() is a shortcut to parseInt( $(this).val() ). Although this is quite handy, it suffers from the same problem as parseInt; namely, if the string starts with a 0, it's parsed as base 8: parseInt("033"); // 27 +"033"; // 27 To be absolutely certain that doesn't happen, use parseInt with base 10: parseInt("033", 10); // 33 so, in our context, you'd use this: total += ( parseInt( $(this).val(), 10 ) || 0 );

Sign up to request clarification or add additional context in comments.

4 Comments

I like the use of + to convert val to an int. This is definitely the best answer.
@GregGuida - While very convinient, there's a catch. See my post.
yeah, I get it but its just so much nicer to look at the first way, haha. you could practically fit it on one line.
@GregGuida - Turns out I was mistaken. +"033" is analogous to Number("033"), which is always parsed in base 10.
2

try this:

$('#mybutton').click(function () {
   var sum = 0;  
    $('input').each(function(){
       var val = parseInt(this.value, 10)
       if (isNaN(val)) { val = 0 }
       sum += val
    })
});

DEMO

Comments

2

Plz try this Workingdemo http://jsfiddle.net/SmRXL/4/ or http://jsfiddle.net/SmRXL/3/

You could use class and iterate it and sum it all.

rest demo will help, `:)

code

$(function() {
    $('#foo').click(function() {
        var total = 0;
        $('.hulk').each(function() {
            if ($(this).val() > 0) total += parseInt($(this).val());
        });
        alert(" TOTAL is => " + total);
    });
});

html

<table>
    <thead>
        <tr>
            <th></th>
            <th>Female</th>
            <th>Male</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Rising 1</td>
            <td>
                <input class="hulk" id="firstinput" />
            </td>
            <td>
                <input class="hulk"  id="secondinput" />
            </td>
        </tr>
        <tr>
            <td>Rising 2</td>
            <td>
                <input class="hulk"  id="thirdinput" />
            </td>
            <td>
                <input class="hulk"  id="fourthinput" />
            </td>
        </tr>
        <tr>
            <td>2+</td>
            <td>
                <input class="hulk"  id="fifthinput" />
            </td>
            <td>
                <input class="hulk"  id="sixthinput" />
            </td>
        </tr>
    </tbody>
</table>

<input type="button" id="foo" value="TOTAL ME" />

1 Comment

Move total to inside the click event, it's being increased all the time.
1
$("#mybutton").click(function(){
alert(addValues($("input")));   
});

function addValues(selector){
    var total = 0;
    selector.each(function(){
        var thisVal = parseInt($(this).val());
        if(!isNaN(thisVal)) total += thisVal;
    });
    return total;
}

use isNaN() to reliably check if a value is not a number.

above I've added it to a function for simplicity.

Comments

1
$('#myButton').click(function() {
    var sum = 0;
    $('table input').each(function(){
        val = parseInt($(this).val(),10);
        sum += isNaN(val) ? 0 : val;
    }
    alert(sum);
}

Be sure to include the radix of 10 in your call to parseInt so that 08 and 09 parse correctly.

Comments

1

In your code, change the parseInt($('#sixthinput').val())'s to parseInt($('#sixthinput').val() || 0). This way, it will return 0 if it is empty, and NaN if the input is invalid.

7 Comments

the || 0 has to go after the parseInt, not in it
@GregGuida that's not the case I'm afraid. Strange as it may be, in JavaScript, the expression "" || 0 will evaluate to 0.
@mikhailvs - But, if there's any non-digit text at the beginning of that string, it'll be truthy, and you'll still end up with NaN.
My point in my previous point was that I realize that I made a typo in my answer, but that I went with it anyway.
Yes, I know. However I maintain that even though I had a typo, my solution is valid. There's a difference between no input and incorrect input, which may need to be handled differently anyway. So if no input means 0, some input (resulting in NaN) may alert the user or something.
|
0

NaN is falsey so you can use the or operator (||) to return the second value if the first is false.

$(document).ready(function () {

        $('#mybutton').click(function () {

            alert(parseInt($('#firstinput').val()) || 0 +
                parseInt($('#secondinput').val()) || 0 +
                parseInt($('#thirdinput').val()) || 0 +
                parseInt($('#fourthinput').val()) || 0 +
                parseInt($('#fifthinput').val()) || 0 +
                parseInt($('#sixthinput').val()) || 0 );
        });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.