23

How do I check if a textarea 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?

3 Answers 3

41

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,"");
}
0
13

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

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

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";
}

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.