Łukasz Szmelc
Łukasz Szmelc

Reputation: 83

Dynamic values in a nested rails form not updating

I'm building restaurant management app and I have an option to add certain dishes to an order. Dishes are picked from a dropdown list and I want a value of a text field to be updated based upon the chosen dish. Just like in that gif.

As you can see in the gif, the value only gets updated when I choose the first field, not the ones that I add dynamically with cocoon gem. My form haml looks as follows:

= simple_form_for @order do |f|
  .meals
    = f.simple_fields_for :meals, @order.meals.build do |meals|
      = render 'meal_fields', f: meals
    .links
      = link_to_add_association 'Add meal', f, :meals
    = f.submit

and in meal_fields.haml partial

.nested-fields
    = f.select(:name, options_for_select(@dishes.map{ |dish| [dish.name, 
{'data-description' => dish.price}]}), {include_blank: true}, {class: 'meal-
name'})
    = f.select :quantity, options_for_select((1..10))
    = f.text_field(:price, disabled: true)
    = link_to_remove_association "X", f

My jQuery code for that looks like that:

$(".meal-name").change(function(){
    var chosen = $(this).find(":selected");
    var price = chosen.data("description");
    $(this).siblings("input").val(price);
})

For me it looks like it should also apply to the updated fields. Is it a bug or a feature? How can I make this code apply to fields I add later as well?

Upvotes: 0

Views: 59

Answers (1)

Unixmonkey
Unixmonkey

Reputation: 18784

jQuery's .change function gets attached to nodes as soon as that code is parsed. New nodes that match the query selector won't have the .change event added to them.

Instead, you can watch a parent object for changes, and have it attach events like this:

$('#order-form').on('change', '.meal-name', function() {
  console.log('a .meal-time changed');
  // your code here
});

Upvotes: 1

Related Questions