I have a textarea and I need to test if the user put a text like " ", or only spaces in it or only " ", I can't accept only spaces, but I can accept " Hi !!". How can I do this in Javascript?
3 Answers
Just trim it and the length will be 0 if it is all spaces.
strname.trim().length == 0
3 Comments
Edie Johnny
This way? $(this).trim().length > 0 But it returned an error, trim needs an argument, shouldn't it be trim($(this)).length > 0 ?
Chris Barlow
trim is a method of a string. Is $(this) a string? Maybe $(this).toString().trim().length depending on the type of this. Or $(this).value.
Chris Barlow
Looking at your question, if $(this) is a textarea, you probably want $(this).value.
You check it like this: demo on JSexample
<script>
var text = ' '
if(text.match(/^\s*$/)){
alert('contains only spaces!')
}
</script>