如何检查 Javascript 或 Jquery 中的 Textarea 是否为空?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2476382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:32:07  来源:igfitidea点击:

How to check if a Textarea is empty in Javascript or Jquery?

javascriptjqueryjavascript-events

提问by streetparade

How do i check if a textarea contains nothing?

如何检查 textarea 是否不包含任何内容?

I tryed with this code

我尝试使用此代码

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

But it doesnt do what i expect. I expect that it should appear a messagebox "debug" and that the textarea is not shown.

但它不符合我的预期。我希望它应该出现一个消息框“调试”并且不显示文本区域。

How can i fix that issue?

我该如何解决这个问题?

回答by Marcos Placona

You wanna check if the value is == "", not NULL.

您想检查该值是否为== "",而不是NULL

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

UPDATE

更新

A working example

一个工作示例

And another one using TRIMin case you wanna make sure they don't post spaces

另外一个使用TRIM如果你想确保他们不交的空间

Implementation for TRIM()

TRIM() 的实现

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

回答by isuru

You can use following jQuery to escape white spaces as well.

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

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

回答by Sarfraz

There is a world of difference between null and empty !

null 和 empty 之间有天壤之别!

Try this instead:

试试这个:

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