开发者

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

开发者 https://www.devze.com 2022-12-24 00:24 出处:网络
How do I check if a textare开发者_运维问答a contains nothing? I tried with this code: if(document.getElementById("field").value ==null)

How do I check if a textare开发者_运维问答a contains nothing?

I tried with this code:

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

But it doesn't 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?


You wanna check if the value is == "", not 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

Implementation for TRIM()

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


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

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


There is a world of difference between null and empty !

Try this instead:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号