user2571510
user2571510

Reputation: 11377

jQuery: Best way to append to html of a paragraph inside a textarea

I have a textarea that contains variable html content which is always wrapped in a paragraph (p) tag.

HTML (before appending):

<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content.</p></textarea>

I fetch this content using the following in jQuery:

jQuery:

$('#comments').val();

Now I need to append HTML at the end of this paragraph but inside the p tag.

HTML (after appending):

<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content. Some appended HTML.</p></textarea>

I can of course replace the last 4 characters of the above (which is the closing p tag), then append my HTML and then add the closing p tag again. Can someone tell me if there is a better way to achieve the same in jQuery ?

Many thanks in advance for this, Tim.

Upvotes: 1

Views: 2665

Answers (4)

nocarrier
nocarrier

Reputation: 129

Ok. I REALLY love this!

$('#comments').text($($('#comments').text()).append(' a new insert!').text());

Don't look at it too long. Could hurt your eyes :-)

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68440

This could do the trick

var html = $('#comments').val();
$('#comments').val(
    $(html).append('  Some appended HTML.')[0].outerHTML
);

DEMO

Upvotes: 2

adeneo
adeneo

Reputation: 318362

Parse the string value of the textarea as HTML, and insert whatever you like, then pass the string value of the HTML back

$('#comments').val(function(_, val) {
    return $('<div />', {html:val}).find('p').append('content').end().html();
});

FIDDLE

Upvotes: 4

Thijs Kramer
Thijs Kramer

Reputation: 1117

You could insert the value into a temporary div, add an element to the <p>-element inside the temporary div and fetch the renewed content again:

var tmpDiv = $('<div></div>'); //create temporary element
tmpDiv.html($('#comments').val()); // add HTML from textarea
$(someHtml).appendTo($('p', tmpDiv)); // append custom HTML to P inside temp element
newTextAreaValue = tmpDiv.html(); // retrieve new value

Upvotes: 0

Related Questions