Question

In my show.html.haml view, I have a form where the user's able to change a few settings. I've just updated to use Rails UJS and, when my users change a drop-down menu, they see the jquery shizzle doing it's thing.

All I've really done in the show.js file is refresh the partial the form sits in and flash an error message.

The problem is that once it's been updated once, the jquery drop-down select doesn't work. I figured this was because it's rendering the update.js view - I therefore included this file. However, still nothing happens and I get no errors in the logs.

In show.html.haml I have (simplified):

#show_form
  = render "show"        

My show partial contains:

= semantic_form_for @product_order, :remote => true do |f| 
  = f.select :shipping_method, options_for_select(ProductOrder::Couriers, :selected => @product_order.shipping_method)

My show.js.erb and update.js.erb contain:

$("#show_form").html("<%= escape_javascript(render("show")) %>");
$("#status_banner").effect("highlight", {}, 3000);
$("#status_banner").html("<h2>ORDER STATUS: <%= (@product_order.state.titlecase) %></h2>");
$("#status_banner").removeClass("alert").addClass("alert <%= (@product_class) %>");

In my product_order.js.coffee I have this:

jQuery ->
  $("#dropdown_select").change ->
    $(this).closest("form").submit()
    $(this).serialize()
    null
    "script"
    false

Like I said, the first action works but fails after the first update. My controller update action is a little bulky but I have made sure I have format.js included. I've also tried putting respond_to :js at the top of my controller.

Am I doing this wrong or is there a simple fix that I'm unable to see?

Was it helpful?

Solution

Your problem is that after you refresh the form, your js isn't firing because technically its a new element in the DOM. You'd need to use jquery event binding like so:

jQuery ->
  $("#dropdown_select").on "change", ->
    $(this).closest("form").submit()
    $(this).serialize()
    null
    "script"
    false
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top