Rustam Gasanov
Rustam Gasanov

Reputation: 15781

JQuery AJAX append to appended element

I am using RoR with AJAX to create posts. So I need an ability to add an 'answers' by previous id.
Every time submit button clicked following code being called

$("<%= selector %>").append("<div id='<%= newanswer %>'><%= escape_javascript(render('answer_layout')) %></div>");

where
selector looks like this #answer-12
newanswer would be #answer-13

First time it works as suggested, but when I click submit second time I need to use already appended #answer-13 div to append newly #answer-14, and it doesn't work. I understand that document doesn't know about first appended element, but have no idea how to resolve this issue. Thanks for any help.

UPDATED I render new answer with edit and destroy links, so I need not only an ability to append which could be workarounded, but fully interact with added elements

Upvotes: 0

Views: 1923

Answers (3)

ABrukish
ABrukish

Reputation: 1452

I can just make a suggestion that you could place somewhere in the DOM your latest used ID:

var appendTo = $('#append-to');    
var appendToId = appendTo.attr('latest');
$( '#' + appendToId ).append("<div id='<%= newanswer %>'><%= escape_javascript(render('answer_layout')) %></div>");

appendTo.attr( 'latest', '<%= newanswer %>' );

Upvotes: 0

Benoit E. LeBlanc
Benoit E. LeBlanc

Reputation: 61

You could also create a wrapper div for all the answers as append adds to the the end of the currently selected element.

So have $('#answer-div').append(etc.....

Instead of $('#specific-answer').append(etc...

Upvotes: 2

gdoron
gdoron

Reputation: 150253

Give all the answers a class, and select the last:

$('.theClass:last').append("<div id='<%= newanswer %>'><%= escape_javascript(render('answer_layout')) %></div>");

Or use this:

$('[id^="answer-"]:last').append("<div id='<%= newanswer %>'><%= escape_javascript(render('answer_layout')) %></div>");

jQuery('[attribute^="value"]')
attribute- An attribute name.
value- An attribute value. Can be either an unquoted single word or a quoted string.

Upvotes: 1

Related Questions