Reputation: 23
I have cocoon gem working and adding\removing partials properly in my app. I added dynamic dropdowns to filter select tags in the partial created by cocoon. The first dropdown uses javascript to filter the second dropdown but only works once and only on the first partial (item) that's created and added by cocoon. Can anyone help me figure out what the best way of making sure this works on every partial created by cocoon is and also that I could change the first dropdown as many times as I want to filter?
This is the partial code created by cocoon every time I add an item:
<script type="text/javascript">
$('.div_add').bind('click', function() {
var allOptions = $('#selectprod option')
$('#selectcat').change(function () {
$('#selectprod option').remove()
var classN = $('#selectcat option:selected').prop('class');
var opts = allOptions.filter('.' + classN);
$.each(opts, function (i, j) {
$(j).appendTo('#selectprod');
});
});
});
</script>
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-6 form-font div_add">
<div class="prodselectbox">
<div class="floatleft cat">Board Type</div>
<div class="floatleft catid">
<select id="selectcat" name="board_type" class="ship_nice_select">
<option value="" class="rhth">Select Board Type</option>
<option>all options for first dropdown</option>
<option class="Some" id="selectionone">Some</option>
<option class="Some2" id="selectionone">Some2</option>
</select>
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-6 form-font div_add">
<div class="floatleft artid">Part Number</div>
<div class="floatleft selectarticle">
<select id="selectprod" name="part_num" class="ship_nice_select">
<option value="" class="rhth23">Select Part Number</option>
<% @items_some = Item.where(board_type: "Some") %>
<% @items_some.each do |i| %>
<option class="selectors Some">
<%= i.part_num %>
</option>
<% end %>
<% @items_some2 = Item.where(board_type: "Some2") %>
<% @items_some2.each do |i| %>
<option class="selectors Some2">
<%= i.part_num %>
</option>
<% end %>
</select>
</div>
</div>
Upvotes: 0
Views: 192
Reputation: 50057
Your view-code seems very incomplete, but from your description I think I can deduce what happens: your javascript binds to the existing .div_add
elements, when clicking the link_to_add_association
and inserting a new partial, those newly inserted .div_add
are not bound to a click-handler.
Two options: cocoon allows to attach callbacks upon insertion (see documentation )
but in your case the better solution is to just write your javascript a little different :
$(document).on('click', '.div_add', function() {
// your handler here
});
Since this handler attaches to the document, this will work correctly for dynamically added .div_add
-elements to the page.
Upvotes: 0