替换为零而不是NaN ...... [英] Replace Zero instead of NaN...............

查看:70
本文介绍了替换为零而不是NaN ......的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我正在使用下面的函数进行计算.唯一的问题是在第一个txtbox中使用输入时,结果显示为NaN,我想显示为零或从第一个txtbox输入值.

Hi
I am using below function, for calculation. Only issue, is during when using input in 1st txtbox, result displays as NaN, I want to display, either Zero, or input value from 1st txtbox.

function show(TxtSTUPort, TxtAAPort, STD_NUM_OF_SERVING) 
{
    var TxtSTUPort = document.getElementById(TxtSTUPort);
    var TxtAAPort = document.getElementById(TxtAAPort);
    var STD_NUM_OF_SERVING = document.getElementById(STD_NUM_OF_SERVING);
    STD_NUM_OF_SERVING.value = (Number(parseInt(TxtSTUPort.value) + parseInt(TxtAAPort.value)));
}

推荐答案

问题是您正在尝试使用它们,就像它们中存在有效的数值一样.在尝试使用这些字段中的值之前,请检查它们是否为NaN,然后再进行所需的数学运算.实际上,我会这样做:

The problem is that you''re trying to use them as if there''s a valid numeric value in them. Before trying to use the values in those fields, check to see if they''re NaN, and only then, do the desired math operations. In fact, I''d do this:

var TxtSTUPort = document.getElementById(TxtSTUPort);    
var TxtAAPort = document.getElementById(TxtAAPort);    
var STD_NUM_OF_SERVING = document.getElementById(STD_NUM_OF_SERVING);
var stuPort = 0;
var aaPort = 0;
var numServing = 0;

if (TxtSTUPort != null && TxtSTUPort.value != null)
{
    stuPort = TxtSTUPort.value;
}
if (TxtAAPort != null && TxtAAPort.value != null)
{
    aaPort = TxtAAPort.value;
}
if (STD_NUM_OF_SERVING != null)
{
    STD_NUM_OF_SERVING.value = stuPort + aaPort;
}



ID还应采取步骤以确保文本字段中的数据是有效的数字数据.我对JavaScript不太了解,但是我确定在某个地方可以执行此操作(并且上面的代码可能需要进行修改,因为我不确定与null进行比较是否在Javascript).



Id also take steps to ensure that the data IN the text fields is valid numeric data. I''m not big on JavaScript, but I''m sure there''s code somewhere to do that (and the code above may need to be tweeked since I''m not sure if comparing against null is valid in Javascript).


更改函数,例如this-
change function like this-
function show(TxtSTUPort, TxtAAPort, STD_NUM_OF_SERVING)
{
    var TxtSTUPort = document.getElementById(TxtSTUPort);
    var TxtAAPort = document.getElementById(TxtAAPort);
    var STD_NUM_OF_SERVING = document.getElementById(STD_NUM_OF_SERVING);
    var stuPort=parseInt(TxtSTUPort.value);
    var aaPort=parseInt(TxtAAPortTxtSTUPort.value);
    stuPort=isNaN(stuPort)?0:stuPort;
    aaPort=isNaN(aaPort)?0:aaPort;
    STD_NUM_OF_SERVING.value = (Number(stuPort + aaPort));
}




--Pankaj



--Pankaj


这篇关于替换为零而不是NaN ......的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆