开发者

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

开发者 https://www.devze.com 2023-02-08 19:07 出处:网络
I have the following: var NewCount = document.getElementById(\'MainContent_gv_NewCount_\' + rowIndex).value;

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 = "";
            }
开发者_Python百科

The calculations I am doing are based on the value in the textbox. (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. However, at the moment it is treating a blank textbox and a textbox with 0 in it the same.

How can I differentiate between the two?


Use !== in your if statement.


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 (!= "").

Here is my attempt: http://jsfiddle.net/pJgyu/5404/


Any of the following could work

NewCount.length > 0
NewCount !== ''


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号