【问题标题】:How to check if a Textarea is empty in Javascript or jQuery?如何检查 Javascript 或 jQuery 中的 Textarea 是否为空?
【发布时间】:2010-03-19 10:13:18
【问题描述】:

如何检查文本区域是否包含任何内容?

我尝试使用此代码:

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

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

我该如何解决这个问题?

【问题讨论】:

    标签: javascript jquery dom-events


    【解决方案1】:

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

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

    更新

    一个working example

    还有another one using TRIM,以防你想确保他们不张贴空间

    TRIM() 的实现

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

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        【解决方案3】:

        There is a world of difference between null and empty !

        试试这个:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-11-07
          • 1970-01-01
          • 2019-04-03
          • 2011-05-05
          • 2012-06-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多