English 中文(简体)
价值是否无效?
原标题:Check if a value is null?

在javascript中,如果没有任何内容的话,我想作一个其他发言,将内容价值(案文领域以html的形式)改为零。 我有:

if(document.getElementById( dollarinput ).value == null){
    var dollars = 0;
}
else{
    var dollars = parseInt(document.getElementById( dollarinput ).value);
}

Something isn t working correctly in the if condition, but I m not sure what I did wrong.

问题回答

您需要将变式声明移至if,并核对空字,如:

var dollars;
if(document.getElementById( dollarinput ).value ==   ){
    dollars = 0;
}
else{
    dollars = parseInt(document.getElementById( dollarinput ).value);
}
  • Value of an input can never be null ! if there is no value, it will be an empty string.
  • alert( == null);​​ // false

<Fixed Code:

if(document.getElementById( dollarinput ).value){
    var dollars = 0;
}
else{
    var dollars = parseInt(document.getElementById( dollarinput ).value);
}
var dollars = 0;
var dollarinput = document.getElementById( dollarinput );
if( ! dollarinput.length )
{
    dollars = parseInt(dollarinput.value);
}

Check if it s an empty string instead:

if(document.getElementById( dollarinput ).value ==   ){
    var dollars = 0;
} else{
    var dollars = parseInt(document.getElementById( dollarinput ).value, 10);
}




相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签