Bob
Bob

Reputation: 8504

jQuery prepending textarea

HTML

<textarea id="photo-42-9" class="comment_box">Write a comment...</textarea>

jQuery code that doesn't work, what am I missing?

$('#photo-42-9').prepend("<div>blah</div>");

EDIT Corrected the ids mismatch, still doesn't work though

Upvotes: 0

Views: 944

Answers (3)

David Thomas
David Thomas

Reputation: 253318

prepend() adds the specified mark-up into the object returned by the jQuery selector (in this case the textarea). A textarea can contain only text, no other child elements; therefore you're trying to create invalid html.

If you want to put the <div> before the textarea:

$('<div>blah</div>').insertBefore('#photo-42-9');

If you want to prepend new text into the textarea:

$('#photo-42-9').val(
    function(i,val){
        return 'blah ' + val;
    });

References:

Upvotes: 4

lonesomeday
lonesomeday

Reputation: 237865

The contents of a textarea element are treated as text, not as HTML. They are parsed into the element's value property. You can't edit the content of the element: you have to edit its value.

The nice, jQuery-ish way of doing this is with val and its callback syntax:

$('#photo-42-9').val(function(i, oldVal) {
    return "<div>blah</div>" + oldVal; // return the desired value
});

jsFiddle

Note that I have also corrected the selector: you had an additional 9 in the ID, so it wouldn't have found the element.

Upvotes: 1

Dutchie432
Dutchie432

Reputation: 29160

@Bob: In addition to what David Thomas said, your item has an id of photo-42-9 and your selector is looking for photo-42-99

Suggested Fix:

$('#photo-42-99').text( $('#photo-42-99').text() + "<div>blah</div>" );

Upvotes: 0

Related Questions