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) {
event.preventDefault();
$.post('/comments', { title: ..., description: ... });
}
});
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') %>").insertBefore(???);
render 'show_comments' returns a <div>stuff</div> that I wish to insert before textarea. I could use the selector on #photo-42-9 but that id is dynamic depending on which textarea element I clicked on. How do I access this object in create.js.erb?
in js:
and in ruby (i guess, I don’t do ruby):
As you see, “this” isn’t passed to rb. Instead, the $.post function waits for the rb response, and pastes it before the text area (the event target). This way is better as all your js code is actually in your js code.
note: “
$(response).insertBefore($this)” would work the same.note: if you move the $this assigination out of the “if”, you can easily check if the fresh comment is not empty and different than the ones already existing (
event.keyCode == 13 && $this.val() != '' && $this.val() != $this.prev().text()). As well, you can empty the textarea with$this.val('')right after the “$this.before” insertion.