0

What is the proper way to extract the value of a textarea in a form via javascript?

var subject = $("input#subject").val();
if (subject == "") {
    $("label#subject_error").show();
    $("input#subject").focus();
    return false;
}
var description = $("textarea#description").val();
if (description == "") {
    $("label#description_error").show();
    $("Textarea#description").focus();
    return false;
}

The $("input#subject").val() works fine but not the $("textarea#description").val(). Must be a noob error I'm missing.

Thank you!

dgvid
  • 26,293
  • 5
  • 40
  • 57
shaiss
  • 2,000
  • 5
  • 22
  • 33

5 Answers5

2

TEXTAREA has innerHTML, not value.

$("textarea#description").html()
Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • 4
    moot point considering OP is using jQuery, which knows this exception and plans accordingly for `.val()` -- **EDIT** [Reference to relative code](https://github.com/jquery/jquery/blob/master/src/attributes.js#L165-169) – Brad Christie Dec 21 '11 at 21:26
  • According to the jQuery documentation and several posts here on SO, `.val()` does indeed work with the textarea-element, even though the element doesn't have a value-attribute. – Christofer Eliasson Dec 21 '11 at 21:28
  • `$("").get(0).value === "a"`, so it actually does have `value` available. – pimvdb Dec 21 '11 at 21:30
1

Your scenario should work fine. Here is a Fiddle.

Are you sure that you have a textarea#description on your page?

nheinrich
  • 1,841
  • 11
  • 17
0

I just tried $('textarea').val() in Chrome Dev Tools on this page can get the value of the textarea, so I'm unsure as to why this isn't working for you.

Indeed, I then just found this: jQuery get textarea text

One other point, you're over-qualifying your selectors by mentioning the element name if they already have an ID. As IDs can only apply to one element on the page, just use the ID in the selector.

Community
  • 1
  • 1
isNaN1247
  • 17,793
  • 12
  • 71
  • 118
0

That ought to work. Can you verify that 1) your textarea element includes attribute id="description" and that 2) no other element on the page has and id of description?

dgvid
  • 26,293
  • 5
  • 40
  • 57
  • Although the others are valid answers. This was the right one in my case. I somehow missed the id="description" in the form. Don't know how I missed that one. – shaiss Dec 22 '11 at 00:57
0
    <html lang="en">
    <head>
    <script type="text/javascript">
        window.onload=function(){
    var txt = document.getElementById("t").value;
    alert(txt);
}
</script>
    </head>

   <body>
     <textarea id="t" rows="30" cols="40"> Hello to text area </textarea>
   </body>
   </html>
Ma7moud El-Naggar
  • 548
  • 1
  • 6
  • 18