Kazik Kazik - 1 year ago 56
Javascript Question

Ajax appended objects not visible in the dom

Hi I have a coffeescript like this:

$(document).on 'change', '#add_skill_form', ->
skill_name = $('#character_skill_of_objects option:selected').text()
if $('#skill_' + skill_name).length == 0
url: 'on_add_skill'
type: 'GET'
dataType: 'script'
data: {
skill_id: $('#character_skill_of_objects option:selected').val()
alert 'Skill already in use'

Inside my view I have some static skills generated, and for them this validation works nice. But when new object is added dynamicly, the validation doesn`t work for him.

This is my add function, where #skill_list is an
, and add_skill partial adds
objects to it:

'<%= form_for [current_user, @character] do |f| %>'
$('#skill_list').append("<%= j render partial: 'add_skill', locals: { character: @character, skill: @skill, f: f } %> ");
'<% end %>'

I assume that the DOM is not reloaded after new object is created.

Answer Source

This seems to be a scope problem. Since new objects are dynamically added, you have to be careful with your binding scope.

The bind actions will "listen" to what you've bound (in this case, the "change").

BUT since you're trying to find the element by itself (i.e: $(element)), the JS will try to find it in the "static DOM" (I mean, it won't care about the DOM modifications that happened after the page first loaded).

So, using a scope, the JS will "listen" to any change inside this scope, and then it'll be able to "listen" to the dynamic modification (i.e: $(some_main_div).find(element)).