如果只选择1,jquery多选设置默认值?

时间:2013-11-13 20:25:54

标签: javascript jquery

假设我在jquery移动解决方案中有多个选择对话框,如下所示:

     <select name="fruitFilter" id=fruitFilter" multiple="multiple" data-native-menu="false">
          <option>Fruit choice</option>
          <option value="1">Choice1</option>
          <option value="2">Choice2</option>
          <option value="3">Choice3</option>
          <option value="4">Choice4</option>
          <option value="1234">All Fruits</option>
        </select>

我希望选择1-4可以单独选择,但如果我选中“所有水果”,我希望所有选择都被标记(禁用是正确的)并且不会被选中 取消选择“所有水果”将使选择1-4再次可选。

截至目前,我已全部工作并加载/保存到localstorage,除非此功能禁用/启用全部/单独

任何人都知道如何做到这一点?

1 个答案:

答案 0 :(得分:0)

可能是这样的吗?

var selAllValue = "1234",
    $fruitSelect = $('#fruitFilter'),
    $allOptions = $fruitSelect.children(), //get all options
    $selAllOption = $allOptions.filter('[value="' + selAllValue + '"]'); //Get the check all option

$fruitSelect.on('change', function () {
    var $this     = $(this),
        currSel   = ($this.val() || []).pop(), //get the last selected value.
        $options  = $allOptions, 
        flg       = (currSel === selAllValue);

    if (flg) { //if it is equal to alloption
       $options = $options.not($selAllOption).prop('selected', false); //unselect others and set $options to the new list
    }

    $options.prop('disabled', flg); //finally set the disable flag on $options. i.e disable flag will be set if current selection is alloption else just not disable all.

    $this.selectmenu('refresh'); //refresh select menu to take effect.

});

<强> Demo