You use an element ID. It is supposed unique in a HTML page. You should be using classes instead.
[UPDATE] Ok. You use global selectors, so you change all elements that have the class.
What you actually want, I guess, is change the elements that were just inserted. As shown in the documentation, this is possible. Just write
$("#items").on "cocoon:after-insert", (e, added_item) ->
added_item.find(".product-select").change ->
$(this).parent().find(".cost-input").val($(this).selected.data("unit_cost"))
This code is not tested, but what I do: attach the change
event. In the change event, use $(this)
, which points to the container triggering the event, and use that as a relative point to find the wanted item.
Please note that this is way easier to solve, if you just use jquery.
$('#items").on "change", ".product-select", ->
product_select = $(this)
product_select.parent().find('.cost_input').val(product_select.selected().data("unit_cost"))
This will capture all change
events, inside #items
that happen on a .product-select
element. Which is dynamic, so it will work for newly added items as well. You might need to fiddle with the jquery a little, to find the selected value. As I said: untested code, but I hope you get the drift.