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

喜夏-厌秋 提交于 2019-12-18 14:19:12

问题


How do i check if a textarea contains nothing?

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?


回答1:


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



回答2:


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

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



回答3:


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


来源:https://stackoverflow.com/questions/2476382/how-to-check-if-a-textarea-is-empty-in-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!