最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the value of a <textarea> if there is no text in it? - Stack Overflow

programmeradmin1浏览0评论

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"/>
发布评论

评论列表(0)

  1. 暂无评论