0

I Have 4 text boxes namely customer_phy_tot, customer_che_tot, customer_bio_tot. I'm trying to add and display all 3 input boxes values to a 4th input, customer_pcb_tot.

customer_bio_obt.blur(function(){
    var customer_pcb_tot = isNaN(parseInt($("#customer_phy_tot").val() + $("#customer_che_tot").val() + $("#customer_bio_tot").val())) ? 0 :( $("#customer_phy_tot").val() + $("#customer_che_tot").val() + $("#customer_bio_tot").val())
    $("#customer_pcb_tot").val(customer_pcb_tot);
});

The problem is instead of adding my code is treating it as a string. Suppose I have values 10, 15 and 5 respectively. It's supposed to display 30 in the 4th box but in my case it is showing 10155.

Any help greatly appreciated.

2
  • 1
    use parseInt for separate values not for all val() + val() Commented Apr 1, 2016 at 14:11
  • total = (parseInt($("#somtthing").val()) || 0) + ... Commented Apr 1, 2016 at 14:14

3 Answers 3

3

You're using parseInt() already, but you need to use it on the string values returned by each individual val() call. Also note that your use of a ternary expression is redundant. Try this:

customer_bio_obt.blur(function() {
    var customer_pcb_tot = parseInt($("#customer_phy_tot").val(), 10) + parseInt($("#customer_che_tot").val(), 10) + parseInt($("#customer_bio_tot").val(), 10);
    $("#customer_pcb_tot").val(customer_pcb_tot || 0);
});
Sign up to request clarification or add additional context in comments.

Comments

3

Use parseInt() function to do this :)

You have to use it to each of your values do make it works.

As @Jamie R Rytlewski said :

Make sure you use the radix value also. parseInt(string, radix);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

9 Comments

But make sure you use the radix value also. parseInt(string, radix); developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
radix is 10 by default
It's still considered best practice to always include it. From MDN: Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior.
stackoverflow.com/questions/850341/… has details on why to always include it as well
but anyway, from MDN references: ecma-international.org/ecma-262/6.0/#sec-parseint-string-radix says (in 10-11) radix should be 10 by default,
|
0

You can parseInt() in each val() that you ask. Or multiply each one for 1 before sum it.

var customer_pcb_tot= isNaN(parseInt($("#customer_phy_tot").val() + $("#customer_che_tot").val() + $("#customer_bio_tot").val())) ? 0 :( $("#customer_phy_tot").val()*1 + $("#customer_che_tot").val()*1 + $("#customer_bio_tot").val()*1)

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.