0

I am trying to get the value of a textarea, to check if it's empty, using Javascript and it doesn't work in Opera. In IE, FF and Chrome it works fine, but in Opera 11 and 10 it reports the value to be the empty string, even if it has text. Here's my code:

if (document.getElementById('mytextareaid').value.replace(/(^\s+|\s+$)/, '') == '') {
    alert('empty textarea');
}

Using document.getElementById('mytextareaid').innerHTML instead, doesn't work, either. What am I missing?

bogdan
  • 671
  • 5
  • 16
  • can you do two things 1. alert(document.getElementById('mytextareaid')); 2. can you append the markup of your textarea to your question. i have tested it in opera and all is well here – naveen Dec 28 '10 at 09:52

3 Answers3

3

Replace with this and try

if (document.getElementById('mytextareaid').innerHTML.replace(/(^\s+|\s+$)/, '') == '') {
    alert('empty textarea');
}
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
  • Try to alert the document.getElementById('mytextareaid').innerHTML before the if condition and also make sure the id of textarea is correct – Shakti Singh Dec 28 '10 at 09:48
  • The alert shows an empty string. Also in Dragonfly I don't see any text in the textarea's dom node. But there is text shown in the textarea in the browser. Any other thoughts? – bogdan Dec 28 '10 at 11:00
  • Check the id of textarea if it is used in document more than once – Shakti Singh Dec 28 '10 at 11:04
  • 1
    You can also check for this property 'nodeValue' document.getElementById('mytextareaid').nodeValue – Shakti Singh Dec 28 '10 at 11:14
  • I am positive I am addressing the right textarea, so using the id more than once is not the issue. nodeValue returns null. Thanks for trying, though. – bogdan Dec 28 '10 at 11:27
1

Thank you all for your help. It turns out that it works with a simple page that only has a textarea, but in my particular HTML document it didn't. I finally found a workaround here: JQuery val() does not work for textarea in Opera I don't know what exactly caused the strange behavior, but I do know that the piece of

Community
  • 1
  • 1
bogdan
  • 671
  • 5
  • 16
0

Quoting myself from JQuery val() does not work for textarea in Opera :

You may have come across a very obscure bug referred to in a blog post on the Opera sitepatching blog ( http://my.opera.com/sitepatching/blog/facebook-and-some-core-patches ) as "PATCH-287, Hack to make script see typed value in TEXTAREA on blog.ebuddy.com. Opera fails to read correct value from a previously hidden textarea".

I'm a little bit reluctant to recomment workarounds without seeing the full code.

However, when I was looking at this I noticed that setting textarea.contentEditable to something seemed to let me read the value afterwards..it's a weird hack though, and it might cause problems for other browsers.

Community
  • 1
  • 1
hallvors
  • 6,069
  • 1
  • 25
  • 43