清除默认选择值`Bootstrap Select2`

时间:2017-12-15 11:49:32

标签: jquery twitter-bootstrap select

我正在使用<amp-analytics type="googleanalytics" id="analytics2"> <script type="application/json"> { "vars": { "account": "UA-XXXXXX-Y" }, "triggers": { "trackClickOnHeader" : { "on": "click", "selector": "#commerce-listing-product", "request": "event", "vars": { "eventCategory": "List Element", "eventAction": "Click", "eventLabel": "{{URL}}", <--- NOT REQUIRED "eventValue": "100millioninionions" <--- NOT REQUIRED } } } } </script> </amp-analytics> ,我需要处理此选择,以便在选择其他选项时清除bootstrap select2的默认选定值。

HTML代码

null

JSCode

<select class="selectpicker" multiple="" name="maritalstatus[]" id="marital-status">
    <option selected="selected" value="">Does Not Matter</option>
    <option value="unmarried">Unmarried</option>
    <option value="divorce">Divorced</option>
    <option value="widow">Widowed</option>
    <option value="awaited-divorce">Awaiting Divorce</option>
</select>

UI

enter image description here

现在根据用户界面,如果我选择$("select").select2({ theme: "bootstrap", containerCssClass: ':all:', dropdownCssClass: 'no-search', allowClear: true, }); 以外的任何选项,则应始终清除Does Not Matter

规则:

  • 不重要选项不能与任何其他选项一起存在。

1 个答案:

答案 0 :(得分:0)

我设法通过以下解决方案解决..

removeDefaultSelect2Value: function() {
  const selectIDs = "#id1, #id2";
  $(selectIDs).on("select2:select", function(e) {
    var $el = $(this);
    var data = e.params.data;
    //console.log(data.element);
    if (data.id === "") {
      $(this).select2("val", 0, true);
    } else {
      setTimeout(function() {
        $el
          .next("span")
          .find(
            'li[title="Does Not Matter"] .select2-selection__choice__remove'
          )
          .click();
      }, 10);
    }
});