I want to show an alert
when a certain function is run and an if statement in that function finds that the <textarea>
has no text in it. I tried:
<textarea rows="10" style="display: block;"id="textLoc" placeholder="Text to test"cols="50"></textarea>
text = document.getElementById('textLoc').value;
if (text == "") {
//show alert
}
but it did not work. Any ideas?
Update: I tried printing the value of the <textarea>
in an alert and it showed the value as undefined. I then tried typeof text == "undefined"
and it did not work either.
I want to show an alert
when a certain function is run and an if statement in that function finds that the <textarea>
has no text in it. I tried:
<textarea rows="10" style="display: block;"id="textLoc" placeholder="Text to test"cols="50"></textarea>
text = document.getElementById('textLoc').value;
if (text == "") {
//show alert
}
but it did not work. Any ideas?
Update: I tried printing the value of the <textarea>
in an alert and it showed the value as undefined. I then tried typeof text == "undefined"
and it did not work either.
- Can you post the rest of the first line? What exactly is "<textarea> value"? – casablanca Commented Nov 6, 2010 at 0:50
- Ok, there you go. Hope it helps – chromedude Commented Nov 6, 2010 at 0:53
4 Answers
Reset to default 3If the <textarea>
element actually exists, value
will be ""
(empty string) if there is no text in it. From your ment on the other answer, "cannot read property of null" means document.getElementById('textLoc')
is returning null
: make sure that the ID of the element is correct.
Javascript is quite flexible. Try:
if (text) {
...
}
You're missing a space before the id
attribute in your HTML, which is why id
is not being set, and hence you can't get an element by that ID.
If you're getting "Cannot read property 'value' of null", then that means there's no element with that ID (i.e., getElementById returned null). If a textarea actually exists, the value is ''
when empty. To safeguard against errors where you access a property of null:
var textarea = document.getElementById('textLoc');
if (textarea && textarea.value) ...
This code:
<textarea rows="10" style="display: block;"id="textLoc"
placeholder="Text to test"cols="50">
is not correct.
The tag should be closed:
<textarea rows="10" style="display: block;"id="textLoc"
placeholder="Text to test"cols="50"/>