user2498559
user2498559

Reputation: 17

Javascript giving NaN error

I am using the below codes:

<script type="text/javascript">
function minus(){
var t=document.getElementById("totalcost").value;
var u=document.getElementById("advpay").value;  
var set=(t-u);
document.getElementById("textfield").value=set;
return true;
}
</script>

I entered "6000" as value in totalcost id field and "1000" in advpay id field. so in textfield id field, it should show 5000 (6000-1000), but it is giving answer as NaN. where is the error ?

Upvotes: 1

Views: 2238

Answers (2)

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

NaN is abbreviated of Not a Number. NaN will be the result of any calculation which contains anything rather than a number (strings, boolean, object). In your case the calculations were made by using 2 strings, That's why it has returned NaN. You have to cast your values into number before doing the calculation.

You can cast your values by using the following piece of code:

Example 1:

 var t = +document.getElementById("totalcost").value;
 u = +document.getElementById("advpay").value;

Example 2 (As @LightStyle suggested):

 var t = parseInt(document.getElementById("totalcost").value, 10),
 u = parseInt(document.getElementById("advpay").value, 10),

Upvotes: 0

Niccol&#242; Campolungo
Niccol&#242; Campolungo

Reputation: 12040

<script type="text/javascript">
function minus() {
    var t = parseInt(document.getElementById("totalcost").value, 10),
        u = parseInt(document.getElementById("advpay").value, 10),
        set = (t - u);
    document.getElementById("textfield").value = set;
    return true;
}
</script>

This is happening because you are trying to subtract two strings! value returns the string of the input, you need to parse it to a number in order to subtract them. Remember to specify radix of parseInt, otherwise the number could be parsed not as a decimal. See this answer for more detailed informations.

Upvotes: 5

Related Questions