admin管理员组

文章数量:1316817

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

本文标签: javascripttextarea value is empty or notcheck with jquery not workingwhyStack Overflow