textarea 值是否为空 - 检查 jquery 不起作用,为什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16757579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:42:45  来源:igfitidea点击:

textarea value is empty or not - check with jquery not working, why

javascriptjqueryhtml

提问by doniyor

i have this code, commentis id of textarea:

我有这个代码,comment是 id textarea

<textarea id="comment">      </textarea>

js

js

var comment = $('#comment').val();
if(comment.length === 0){
    alert('empty');
    return;
}else{
    alert('not empty');
}

it is giving me not empty even if it is empty. why is this? i cannot check like !=""because whitespace will pass the check and i would have to check for all whitespaces then

即使它是空的,它也给我不空。为什么是这样?我无法检查,!=""因为空格会通过检查,然后我必须检查所有空格

please help

请帮忙

回答by PSL

Remove space in your textarea or trim the value

删除文本区域中的空间或修剪值

<textarea id="comment"></textarea>

or

或者

var comment = $.trim($('#comment').val());

Also btw if you are returning after ifyou dont need an else

顺便说一句,如果您在if不需要后返回else

 var comment = $.trim($('#comment').val());
if(comment.length == 0){
    alert('empty');
    return;}

 alert('not empty');

回答by Niccolò Campolungo

I bet it does the opposite of what you expect, right?

我敢打赌它与您期望的相反,对吗?

I think you need to study how it works, even if it is a logical problem. If the length of the string is 0 it is empty, otherwise it is not.

我认为你需要研究它是如何工作的,即使它是一个逻辑问题。如果字符串的长度为 0,则为空,否则为空。

var comment = $.trim($('#comment').val());
if(comment.length === 0){
    alert('empty');
    return;
}
alert('not empty');

回答by techfoobar

Should work if you trim()the value before checking its length.

如果您trim()在检查其长度之前使用该值,则应该可以工作。

var comment = $.trim($('#comment').val());
if(comment.length !== 0) {
   ...

回答by Arun

You need to trim the value before checking and it can be done in one line

您需要在检查之前修剪该值,并且可以在一行中完成

alert($.trim($('#comment').val()) == "" ? "Empty" : "Not Empty");