【问题标题】:Chosen Multiple Select - Unselect "All" option when selecting anything else, and vice versa选择多项选择 - 选择其他任何内容时取消选择“全部”选项,反之亦然
【发布时间】:2013-01-19 03:14:44
【问题描述】:
我正在使用带有“全部”选项的选择多项选择。
Referring to this
基本上我想要发生的事情如下:
-
如果用户选择“全部”以外的任何选项,我希望自动取消选择“全部” - 工作使用此:
if ($('#customTextFilterSelect option[value="ALL"]').attr('selected') == 'selected'
&& $("#customTextFilterSelect option:selected").length > 1) {
$('#customTextFilterSelect option[value="ALL"]').removeAttr("selected");
}
我还希望相反的工作 - 如果用户选择“全部”,我希望自动取消选择其他选项。 不确定如何最好地实施
-
最后,如果用户取消选择所有内容(手动,通过单击“x”),应自动选择“全部”。 类型的工作,但占位符回到“全部”时回来,因为长度== 0
if ($("#customTextFilterSelect option:selected").length == 0) {
$('#customTextFilterSelect option[value="ALL"]').attr('selected', 'selected');
}
【问题讨论】:
标签:
javascript
jquery
jquery-chosen
【解决方案1】:
解决办法如下:
$(function()
{
var cSelect = $('.chzn-select').chosen();
var allItem = cSelect.find("option[value='ALL']"); //reference to the "ALL" option
var rest = cSelect.find("option[value!='ALL']"); //reference for the rest of the options
var allItemAlreadySelected = true; //set a flag for the "ALL" option's previous state
cSelect.change(function(event)
{
if ($(this).find("option:selected").length == 0) //if no selection
{
allItem.prop('selected', true); //select "ALL" option
}
else
{
if (allItem.is(':selected')) //currently "ALL" option is selected, but:
{
if (allItemAlreadySelected == false) //if previously not selected
{
rest.prop('selected', false); //deselect rest
allItem.prop('selected', true); //select "ALL" option
}
else //if "ALL" option is previously selected (already), it means we have selected smthelse
allItem.prop('selected', false); //so deselect "ALL" option
}
}
allItemAlreadySelected = allItem.is(':selected'); //update the flag
$('.chzn-select').trigger("liszt:updated"); //update the control
});
});
现在,您根本不需要那个占位符。控件现在永远不会为空。因此,要摆脱占位符,您所要做的就是;将此属性添加到您的 select。
data-placeholder=" "
它的值应该有一个空格,否则选择可能会覆盖它。
<select data-placeholder=" " id="customTextFilterSelect" multiple='multiple' style="width:350px;" class="chzn-select">
这里是working code on jsFiddle。
【解决方案2】:
使用以下 javascript 来执行此操作。
$(function () {
//Defining the 'ALL' as default option.
var prevdata = ["ALL"];
$('.chzn-select').chosen().change(function(e) {
if ($(this).find("option:selected").length === 0) {
$(this).find("option[value='ALL']").attr('selected', 'selected');
} else {
var cur_date = $(this).val();
if ($(this).find("option[value='ALL']").attr("selected") == "selected" && $(this).find("option:selected").length > 1)
$(this).find("option[value='ALL']").removeAttr("selected");
if(( $.inArray('ALL', prevdata) == -1) && $.inArray('ALL', cur_date) > -1){
$(this).find('option').removeAttr('selected');
$(this).find("option[value='ALL']").attr("selected", "selected");
}
}
$('.chzn-select').trigger("liszt:updated");
//Storing the current processed value
prevdata = $('#customTextFilterSelect').val();
});
});
以下是jsFiddle链接
http://jsfiddle.net/qCzK9/7/