admin管理员组文章数量:1394740
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;
}
版权声明:本文标题:html - how to avoid NaN in the text box before adding the other text box values in javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744640529a2617091.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论