My setup: Rails 3.0.9, Ruby 1.9.2, jQuery 1.6.2
HTML
<textarea id="photo-42-9" class="comment_box">Write a comment...</textarea>
jQuery
$('#newsfeed').delegate('.comment_box', 'keydown', function (event){
if(event.keyCode == 13) {
var $this = $(event.target);
$.post('/comments', { title: ..., description: ... }, function(response) { $(response).insertBefore($this); }, "script");
}
});
Rails
comments_controller.rb
def create
@comment = Comment.new
respond_to do |format|
format.html # new.html.erb
format.js
end
end
create.js.erb
"<%= escape_javascript( render 'show_comments') %>"
render 'show_comments' returns a <div>...</div> that I wish to insert before textarea. What I found is that the special characters escaped in the output aren't rendered properly by JS, ideas? This is what it looks like currently in HTML after insertBefore
<div class="\"comment\"">(Bob less than a minute ago) beautiful day<\/div></div>
I just noticed that an extra </div> is added to the end of the output, seemingly by jQuery because this is what create.js.erb spits out as shown in Firebug console response
'<div class=\"comment\">(Bob less than a minute ago) beautiful day<\/div>'