Keith L.
Keith L.

Reputation: 2124

jQuery saving string with .text() + JSON and reading with .val() loses line breaks

I'm sending and retrieving data to view it in a <textarea>.

sending:

$.ajax({
           url: "./xxx/xxx",
           type: "POST",
           dataType: "json",
           data: JSON.stringify({
           text: $('#txtText').text(),
           xxx: $('#xxx').text()
        })

retrieving

if (data.d.Text != "") {
        $('#txtText').val(data.d.Text);
}

The result is the correct text that was sent, but without line breaks. I need the line breaks displayed correctly.

I've played around with .text(), .html() and .val() but couldn't figured it out.

I'm using jQuery 1.7.2

Upvotes: 2

Views: 1392

Answers (2)

Alnitak
Alnitak

Reputation: 339927

You should use .val() to retrieve the contents too, not .text().

The latter will only retrieve the value that was in the page as downloaded from the server.

Any subsequent edits only alter the .value property of the field, and not the contents of the field's text node children.

Upvotes: 1

Ganesh Bora
Ganesh Bora

Reputation: 1153

Add code to replace <br/> to new line \n character

text_str = data.d.Text
text_str = text_str.replace("<br/>","\n"); 
$('#txtText').val(text_str);

Upvotes: 0

Related Questions