简体   繁体   English

删除变量时从输入字段中删除NaN

[英]Remove NaN from input field when removing variable

I'm making a simple calculator and i have a bit of code that i got from a previous question: 我正在做一个简单的计算器,我有一个从上一个问题中得到的代码:

$("input[type=text]").keyup(function () {
        var number = parseFloat($(this).val());
        var inc = parseFloat($(this).attr("inc"));
        var newValue = number / inc;
        $("input[type=text]").each(function () {
                $(this).val(newValue * parseFloat($(this).attr("inc")));
                });
        });

When i enter a value then delete it the box's equal NaN, i just need to know how to stop it from displaying it and display 0 in its place. 当我输入一个值然后将其删除时,该框的数值等于NaN,我只需要知道如何阻止它显示它并在其位置显示0。

JSFiddle Here JSFiddle在这里

You can use isNaN(val) : to check if its number is illegal. 您可以使用isNaN(val) :检查其编号是否非法。

$("input[type=text]").each(function () {
if(isNaN(newValue * parseFloat($(this).attr("inc"))))
  $(this).val(0);
else
  $(this).val(newValue * parseFloat($(this).attr("inc")));
});

Working Demo 工作演示

Test if the number if NaN before using it: 在使用前测试数字是否为NaN

var number = parseFloat($(this).val());
if (isNaN(number)) {
    number = 0;
}

Test the value using isNaN() this will allow you to alter the output 使用isNaN()测试值,这将允许您更改输出

http://jsfiddle.net/J24yN/153/ http://jsfiddle.net/J24yN/153/

        newValue * parseFloat($(this).attr("inc"))

        if(!isNaN(newValue)){
            $(this).val(newValue);
        } else {
            $(this).val(0);
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM