1

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 ?

2 Answers2

5
<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.

Community
  • 1
  • 1
Niccolò Campolungo
  • 11,824
  • 4
  • 32
  • 39
0

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),
cassmtnr
  • 927
  • 13
  • 26
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130