f.select + javascript 从 select 菜单中添加和删除 div 样式

f.select + javascript to add and remove div styles from select menu

我是 Rails 的新手,也是 Javascript 的新手。
我正在尝试使用 f.select 菜单更改 div class 上的显示样式。如果在 select 菜单上设置了相关值,我将尝试仅显示二级菜单。

此表格用于选择家具类型。主要 select 有 3 个选项:桌子、椅子和沙发。如果 "table" 是 selected,那么我希望能够显示另一个表格类型的菜单(落叶、咖啡、结束等)。

我正在使用 Select2 gem...所以这可能是相关的。我可以使用常规的旧 HTML select 菜单来完成这项工作...但不能使用 f.select。这是我的代码

CSS

#tableObject, #chairObject, #couchObject {
display:none;
}

形式

    <%= f.select :furniture, options_for_select([
['FURNITURE TYPES' ,''],

['Chairs' ,'Chairs'],
['Tables' ,'Tables'],
['Couches' ,'Couches']

    ]), {}, { style: 'width:300px', id: 'furnitures'} %>

<div id="couchObject">
    "List of Couches"
</div>

<div id="chairObject">
    "List of Chairs"
</div>

<div id="tableObject">
    "List of Tables"
</div>

javascript

<script>
  $('#furnitures').change(function() {
    if ( $(this).val() == 'Chairs') $('#chairObject').css('display', 'block');
    else $('#chairObject').css('display', 'none');

});
   $('#furnitures').change(function() {
    if ( $(this).val() == 'Couches') $('#couchObject').css('display', 'block');
    else $('#couchObject').css('display', 'none');

});

    $('#furnitures').change(function() {
    if ( $(this).val() == 'Tables') $('#tableObject').css('display', 'block');
    else $('#tableObject').css('display', 'none');

});

 </script>

更新:HTML输出

<div class="select2-container" id="s2id_titles" style="width: 300px;"><a href="javascript:void(0)" class="select2-choice" tabindex="-1">   <span class="select2-chosen" id="select2-chosen-2">Tables</span><abbr class="select2-search-choice-close"></abbr>   <span class="select2-arrow" role="presentation"><b role="presentation"></b></span></a><label for="s2id_autogen2" class="select2-offscreen"></label><input class="select2-focusser select2-offscreen" type="text" aria-haspopup="true" role="button" aria-labelledby="select2-chosen-2" id="s2id_autogen2"></div><select style="width: 300px; display: none;" id="titles" name="participant[title]" tabindex="-1" title=""><option value="">Furnitures</option>
<option value="Tables">Tables</option>
<option value="Chairs">Chairs</option>
<option value="Couches">Couches</option>
</select>
</div>

<div id="couchObject">"List of Couches"</div>
<div id="chairObject">"List of Chairs"</div>
<div id="tableObject">"List of Tables"</div>

尝试

$('#furnitures').select2({}).on('change', function () {
    var val = $(this).select2('val');
    $('#couchObject').toggle(val == 'Couches');
    $('#chairObject').toggle(val == 'Chairs');
    $('#tableObject').toggle(val == 'Tables');
});

演示:Fiddle