简体   繁体   English

如何在JavaScript中区分空白文本框和文本框中的零?

[英]How can I tell between a blank textbox and a textbox with zero in it in JavaScript?

I have the following: 我有以下内容:

var NewCount = document.getElementById('MainContent_gv_NewCount_' + rowIndex).value;
if (NewCount != "") {
    document.getElementById('MainContent_gv_lblTotal_' + rowIndex).innerHTML = "£" + ((originalCount - NewCount) * unitCost).toFixed(2);
} else { 
   document.getElementById('MainContent_gv_lblTotal_' + rowIndex).innerHTML = "";
            }

The calculations I am doing are based on the value in the textbox. 我正在进行的计算基于文本框中的值。 (NewCount). (NewCount)。

I want the label to update if the value is any number (including 0), but to be wiped if the user clears the textbox. 我希望标签在值为任意数字(包括0)时更新,但如果用户清除文本框则要擦除。 However, at the moment it is treating a blank textbox and a textbox with 0 in it the same. 但是,目前正在处理空白文本框和文本框中的0相同。

How can I differentiate between the two? 我如何区分这两者?

if语句中使用!==

I can't reproduce the behavior you are describing. 我无法重现您描述的行为。 In my tests a textbox with "0" in it will be considered not blank by Javascript using your comparison logic (!= ""). 在我的测试中,在为“0”的文本框会使用比较逻辑(!=“”)被认为不会有 JavaScript的空白。

Here is my attempt: http://jsfiddle.net/pJgyu/5404/ 这是我的尝试: http//jsfiddle.net/pJgyu/5404/

if ( NewCount.length == 0 ) {
    // text-box is empty
} else if ( !isNaN(NewCount) ) {
    // the value is a number
}

Any of the following could work 以下任何一种都可以

NewCount.length > 0
NewCount !== ''

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

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