我的网页上有一个像这样的选择选择器元素:
<select id="difficulty" name="difficulty" class="selectpicker" multiple onchange="ChangeFilters()">
<option value="-1" selected >All</option>
<option value="0" >Facile</option>
<option value="1" >Normal</option>
<option value="2" >Difficile</option>
</select>
当用户选择&#34;全部&#34; options(value =&#39; -1&#39;),如果选择了其他选项,则它们不会被选中,如果在用户选择其他选项时选择了all,则选择&#34; all选项&#34;没有被选中。
我已经搜索了2个小时,但我无法正常工作。
我使用bootstrap,这个select元素是一个selectpicker元素,当我尝试某些东西时,我的javascript不起作用..
请帮忙!
编辑:
我发布了工作代码作为答案,感谢您的帮助!
答案 0 :(得分:2)
这样的东西?
function ChangeFilters(){
var selVal = $('#difficulty').val()[0];
if(selVal == -1){
$('#difficulty').attr('multiple',false);
}else{
$('#difficulty').attr('multiple',true);
}
}
答案 1 :(得分:0)
借助此帖Select all / Unselect all in Bootstrap Select plugin
这是完整的工作代码,允许用户选择All选项,3个困难或什么都没有:
HTML:
<select id="difficulty" name="difficulty" class="selectpicker" multiple onchange="ChangeFilters()">
<option value="All" selected >Tous</option>
<option value="0" >Facile</option>
<option value="1" >Normal</option>
<option value="2" >Difficile</option>
</select>
Javascript:
//This need to be on your page load or other load event before the first onChange.
$('#difficulty').data('allOptionIsSelected', true);
function ChangeFilters() {
if ($('#difficulty') != null) {
if ($('#difficulty').val() != null) {
var allOptionIsSelected = ($('#difficulty').val() || []).indexOf("All") > -1;
function valuesOf(elements) {
return $.map(elements, function (element) {
return element.value;
});
}
if ($('#difficulty').data('allOptionIsSelected') != allOptionIsSelected) {
//User clicked 'All' option
if (allOptionIsSelected) {
$('#difficulty').selectpicker('val', ["All"]);
$('#difficulty').selectpicker('refresh');
} else {
}
} else {
// User clicked other option
if ($('#difficulty').val().length != $('#difficulty').find('option').length) {
//user clicked other
// All options were selected, user deselected one option
// => unselect 'All' option
$('#difficulty').selectpicker('val', valuesOf($('#difficulty').find('option:selected[value!=All]')));
allOptionIsSelected = false;
}
}
$('#difficulty').data('allOptionIsSelected', allOptionIsSelected);
}
$('#difficulty').selectpicker('refresh');
}
}
如果您希望将此功能与项目配合使用,请将“#difficulty”更改为您选择控件的ID。
感谢@ yuriy636以前的帮助:)