Reputation: 753
I implemented a feature where a user can update an objects attribute to true/false directly from the table output on click. Everything is working as it should for the first time, but after the ajax call is being done I cannot do it anymore. Maybe the DOM failed to load?
I have my table:
<div id="dashboard_pages_table" class="small-12 columns">
<%= render partial: 'layouts/admin/dashboard_pages_table', locals: {parents: @parents} %>
</div>
And the coffeescript which is listening to a click event on one td element:
jQuery ->
$('#sortable .onoff').on "click", (event) ->
page_id = event.target.parentElement.parentElement.id.match(/\d+$/)[0]
$.post 'update_row_onoff',
page_id: page_id
The coffeescript is calling the update_row_onoff method in my controller:
def update_row_onoff
@target_page = Page.find(params[:page_id])
if @target_page.active
@target_page.update_attribute(:active, false)
else
@target_page.update_attribute(:active, true)
end
respond_to do |format|
format.js
end
end
And then the update_row_onoff js.erb file is reloading the contents of the dashboard_table:
$('#dashboard_pages_table').html("<%= escape_javascript(render partial: 'layouts/admin/dashboard_pages_table', locals: {parents: @parents}) %>");
Why is it not working after the first successful post action?
Upvotes: 2
Views: 726
Reputation: 17834
Use this instead
$("body").on "click", "#sortable .onoff", (event) ->
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.
For details go to the api documentation, http://api.jquery.com/on/
Upvotes: 4