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

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


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.

但它没有做我所期望的。我希望它应该出现一个消息框“debug”,并且textarea不会显示。

How can i fix that issue?

我该如何解决这个问题?

3 个解决方案

#1


22  

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 TRIM in 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,"");
}

#2


3  

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

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

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

#3


0  

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";
}
智能推荐

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2010/03/19/3a66f127b8d094e166332d1a7978a94b.html



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告