如何在Javascript或jQuery中检查Textarea是否为空?

23

如何检查一个文本域是否为空?

我尝试了以下代码:

if(document.getElementById("field").value ==null)
{
    alert("debug");
    document.getElementById("field").style.display ="none";
 }

但它没有做我期望的事情。 我期待出现一个名为“debug”的消息框,同时不显示文本区域。

我该如何解决这个问题?

3个回答

41

你想检查的是值是否为== "",而不是NULL

if(document.getElementById("field").value == '')
{
    alert("debug");
    document.getElementById("field").style.display ="none";
}

更新

这里有一个可工作的例子

如果您想确保他们不发布空格,请使用另一个使用TRIM的示例

TRIM()实现

String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
}

13

你可以使用以下 jQuery 来转义空格。

if($("#YourTextAreaID").val().trim().length < 1)
{
    alert("Please Enter Text...");
    return; 
}

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接