admin管理员组

文章数量:1332873

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.

Share Improve this question edited Nov 6, 2010 at 0:58 chromedude asked Nov 6, 2010 at 0:30 chromedudechromedude 4,30216 gold badges69 silver badges96 bronze badges 2
  • 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
Add a ment  | 

4 Answers 4

Reset to default 3

If 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"/>

本文标签: javascriptWhat is the value of a lttextareagt if there is no text in itStack Overflow