最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

i have this code, comment is id of textarea:

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

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

i have this code, comment is id of textarea:

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

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

Share Improve this question edited May 26, 2013 at 8:48 doniyor asked May 26, 2013 at 8:42 doniyordoniyor 37.9k61 gold badges180 silver badges270 bronze badges 1
  • Are you basically asking how to check if the value is empty except for whitespace? – John Dvorak Commented May 27, 2013 at 11:31
Add a comment  | 

4 Answers 4

Reset to default 10

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 if you dont need an else

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

 alert('not empty');

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.

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

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

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

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

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论