twitter-bootstrap 选择空选项时引导选择清除

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28072175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 22:11:39  来源:igfitidea点击:

Bootstrap-select clear when chosen empty option

jquerytwitter-bootstrapbootstrap-select

提问by Pantela

I'm using bootstrap-selectlike this:

我正在使用这样的引导选择

<select name="country_key" class="show-menu-arrow" multiple
        data-container="body" data-width="250px" >
    <option value="">-clear-</option>
    <option value="1">USA</option>
    <option value="2">Russia</option>
    <option value="3">China</option>
    <option value="4">Spain</option>
</select>

I can select multipleoptions, but I also need to clear which options I chosen.

我可以选择multiple选项,但我还需要清除我选择的选项。

For example, if I choose USAand Spain, when I click -clear-, I need to clear the other options and close the dropdown.

例如,如果我选择USASpain,当我点击 时-clear-,我需要清除其他选项并关闭下拉菜单。

Any idea how to do this?

知道如何做到这一点吗?

回答by KyleMit

You can programmatically clear the selected options by calling .selectpicker('deselectAll').

您可以通过调用以编程方式清除所选选项.selectpicker('deselectAll')

You'll also need to tap into the change event for the select box to see if you need to call into the method. To do that, just monitor the changeevent on the original select element.

您还需要点击选择框的更改事件以查看是否需要调用该方法。为此,只需监视change原始选择元素上的事件

$('#country_key').on('change', function(){
  if (this[0].selected) {
    $(this).selectpicker('deselectAll');
  }
});

Demo in Stack Snippets

堆栈片段中的演示

$('#country_key').on('change', function(){
  if (this[0].selected) {
    $(this).selectpicker('deselectAll');
  }
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>

<select id="country_key" data-container="body" 
        class="selectpicker show-menu-arrow" data-width="250px" multiple>
    <option value="" >-clear-</option>
    <option value="1">USA</option>
    <option value="2">Russia</option>
    <option value="3">China</option>
    <option value="4">Spane</option>
</select>