Javascript文本框值输出NAN on.Change

时间:2014-01-30 05:15:32

标签: javascript jquery

我真的很喜欢javascript并尝试使用Google搜索。但我没有找到任何运气。 每次我在文本框中输入一个值时,请帮助我。其他文本框将显示“nan”然后当我尝试更改NaN值时,我输入的第一个文本框将返回值的前1000位数。

这是我的问题的Fiddle

这些是我的代码

$(document).on('change', '#family_home,#home_contents,#motor_vehicle,#Total', function() {
updateTotal();
    });       
var updateTotal =function() {
var a = parseInt($('#family_home').val());
$('#family_home').val(a.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
var b = parseInt($('#home_contents').val());
$('#home_contents').val(b.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
var c = parseInt($('#motor_vehicle').val());
$('#motor_vehicle').val(c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
var total = parseInt(a)+parseInt(b)+parseInt(c);   
$("#Total").html(total);         
};  

请帮忙。谢谢。我知道我是新手,但我想从你们那里获得更多的知识。所以请把它传给我。感谢

2 个答案:

答案 0 :(得分:0)

NaN属性是表示“非数字”的值。要避免代码中出现这种情况,可以使用isNaN()函数:

$(document).on('change', '#family_home,#home_contents,#motor_vehicle,#Total', function() {
    updateTotal();
    });       
var updateTotal =function() {
var a = parseInt($('#family_home').val());
    $('#family_home').val(a.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
var b = parseInt($('#home_contents').val());
    if (!isNaN(b))
    $('#home_contents').val(b.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
var c = parseInt($('#motor_vehicle').val());
    if (!isNaN(c))
    $('#motor_vehicle').val(c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
var total = parseInt(a)+parseInt(b)+parseInt(c);   
    $("#Total").html(total);         
};  

http://jsfiddle.net/hescano/zzxwV/6/

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

答案 1 :(得分:-1)

请使用此代码:

$(document).on('change', '#family_home,#home_contents,#motor_vehicle,#Total', function() {
    updateTotal();
    });       
    var updateTotal =function() {
    var re=new RegExp(",","g");
    var a = parseInt($('#family_home').val().replace(re,""),10);
    if(!isNaN(a))
    $('#family_home').val(a.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    var b = parseInt($('#home_contents').val().replace(re,""),10);
    if (!isNaN(b))
    $('#home_contents').val(b.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    var c = parseInt($('#motor_vehicle').val().replace(re,""),10);
    if (!isNaN(c))
    $('#motor_vehicle').val(c.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","));
    var total = parseInt(a)+parseInt(b)+parseInt(c);   
    $("#Total").html(total);         
};