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
4 Answers
Reset to default 10Remove 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");