开发者

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


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:

  • prepend().
  • insertBefore().
  • val().


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.


@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>" );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜