10

我编写了一个带有文本框和提交按钮的简单 html 文件,它会根据您提交的内容生成和 document.write 的响应。我想让它生成一个响应,说如果该框为空则输入内容。文本框的 id 是 chatinput,所以我在开头有以下代码

    var chatinput_box=document.getElementById('chatinput');
    var chatinput=chatinput_box.value;

然后有一个条件,虽然我不能让它正常工作;我试过了

    if(chatinput==""){}
    if(chatinput.length=0){}
    if(chatinput=null){}

和其他人,但没有一个工作正常。有人有其他想法吗?

4

2 回答 2

19

应该是这样的:

var chatinput = document.getElementById("chatinput").value;
if (chatinput == "" || chatinput.length == 0 || chatinput == null)
{
    // Invalid... Box is empty
}

或简写:

if (!document.getElementById("chatinput").value)
{
    // Invalid... Box is empty
}

=分配一个值,同时检查这些==值是否相等。

于 2013-11-08T15:17:07.953 回答
3

只是提供一个替代方案,而不是试图窃取雷声......

创建一个isEmpty函数以重用各种项目。

function isEmpty(val){
    return ((val !== '') && (val !== undefined) && (val.length > 0) && (val !== null));
}

然后你可以将它应用到你想要的任何元素上:

if(!isEmpty(chatinput)){
    // hooray its got a value!
}

不完全是原创的,它的概念是从 PHP 中偷来的,但它派上用场了很多。

于 2013-11-08T15:22:43.830 回答