我是Rails的新手,也是Javascript的新手
我正在尝试使用f.select菜单更改div类的显示样式。如果在选择菜单上设置了相关值,我只想显示辅助菜单。
表格用于挑选各类家具。主要选择有3个选项:桌子,椅子和沙发。如果选择“table”,那么我希望能够显示另一种类型的表格(drop leaf,coffee,end..etc)。
我正在使用Select2 gem ......所以这可能是相关的。我可以使用常规的旧HTML选择菜单...而不是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>
答案 0 :(得分:1)
尝试
$('#furnitures').select2({}).on('change', function () {
var val = $(this).select2('val');
$('#couchObject').toggle(val == 'Couches');
$('#chairObject').toggle(val == 'Chairs');
$('#tableObject').toggle(val == 'Tables');
});
演示:Fiddle