1

I have a textarea with an id of posttext.

I am trying to get the values of the textarea, but .html() and .text() always returns null in Production. But .val() returns the correct value. I am using IIS as the web server.

alert($("#posttext").html());    // returns empty
alert($("#posttext").val());     //returns the correct values
alert($("#posttext").text());    // returns empty

The code works fine when i run it locally, so is there any settings that is messed up in production ? Any way to debug ? Since its an ajax loaded form, i cannot see the textarea in view source.

Thanks

Deepu Sasidharan
  • 5,193
  • 10
  • 40
  • 97
user636525
  • 3,180
  • 9
  • 38
  • 51

3 Answers3

6

In jQuery, you use .val() to access the contents of a textarea. That's how jQuery works. You don't use .html() or .text(). Your solution seems simple enough. Just use .val().

.html() and .text() return to you the values that were in the original HTML which is the initial value for the textarea, NOT the currently typed value.

http://jsfiddle.net/jfriend00/zV5zM/

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Does .val() from a textarea retains all the line break, line spacing etc, exactly the way the user entered ? I am using this textarea as a comment box. – user636525 Jan 08 '14 at 05:24
  • 1
    @user636525 -yes it retains what was typed. That is it's purpose. – jfriend00 Jan 08 '14 at 05:25
  • @jfriend00 then what is the correct way to get the innerhtml of a div.id if it was updated dynamically later? – Amit Shah Aug 16 '16 at 10:00
2

It is not about local environment or production environment.

Problem is this: html() will always give you initial values and val() will give you the actual value present/written in textarea. See this Jsbin Demo

HTML

<textarea id="ta"> This is html of textarea </textarea>

JS

var $t = $('#ta');
console.log($t.html());

$t.val('New html content of textarea');

console.log($t.html()); //  This is html of textarea
console.log($t.text()); //  This is html of textarea
console.log($t.val()); // New html content of textarea
Sachin Jain
  • 21,353
  • 33
  • 103
  • 168
1

.html() & .text() will only give you the result that you added while coding.

For example : I added text between text area as : <textarea name ="editor" id="editBox" rows="5" cols="2">aeflljn</textarea> while coding.

So it will show : aeflljn.It will not alert changes that you make in the textbox.

See this fiddle

So the only way to get correct value is to use .val()

Zword
  • 6,605
  • 3
  • 27
  • 52