am using the following code to add text box values if any of the textbox is not given value it is showing NaN in total textbox how to avoid it
<script>
function totalValue()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = parseFloat(a)+ parseFloat(b)+ parseFloat(c);
document.getElementById("total").value = d;
}
</script>
am using the following code to add text box values if any of the textbox is not given value it is showing NaN in total textbox how to avoid it
<script>
function totalValue()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = parseFloat(a)+ parseFloat(b)+ parseFloat(c);
document.getElementById("total").value = d;
}
</script>
Share
Improve this question
edited Jul 31, 2013 at 7:21
Dhaval Marthak
17.4k6 gold badges48 silver badges69 bronze badges
asked Jul 31, 2013 at 7:18
user2419839user2419839
631 gold badge3 silver badges9 bronze badges
3
- what do you mean? if value of a is not given, d has the sum of only b and c? – Lonely Commented Jul 31, 2013 at 7:20
-
3
parseFloat('0' + a)
– meze Commented Jul 31, 2013 at 7:20 - but it is not adding those two and giving output as NaN – user2419839 Commented Jul 31, 2013 at 7:21
3 Answers
Reset to default 6Try this:
<script>
function totalValue()
{
var a = document.getElementById("a").value || 0;
var b = document.getElementById("b").value || 0;
var c = document.getElementById("c").value || 0;
var d = parseFloat(a)+ parseFloat(b)+ parseFloat(c);
document.getElementById("total").value = d;
}
</script>
Fiddle: http://jsfiddle/AvzwM/
You can append a 0
to a string:
<script>
function totalValue()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var d = parseFloat('0' + a)+ parseFloat('0' + b)+ parseFloat('0' + c);
document.getElementById("total").value = d;
}
</script>
<script>
//checks if given text in text box is a number or unwanted string
filterInt = function (value)
{
if(/^\-?[0-9]+$/.test(value))
return Number(value);
return NaN;
}
function totalValue()
{
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
a=filterInt(a)||0; //if it is a string, convert it to a Nan and then if NaN, convert to zero
b=filterInt(b)||0;
c=filterInt(c)||0;
var d = parseFloat(a)+ parseFloat(b)+ parseFloat(c);
document.getElementById("total").value = d;
}