选择指定值时,清除select2倍数

时间:2017-05-17 11:33:01

标签: javascript jquery jquery-select2

我尝试在select2 multiple select中实现以下场景。

  1. 用户选择一些选项
  2. 用户在选择
  3. 中选择“无需要的程序”
  4. 选择清除所有选定的值
  5. Select有一个占位符,其中包含以下文本:'No Required Features'
  6. 这是我的HTML:

    <select multiple="multiple" name="transfer_posting[pap_facility_feature_ids][]" id="transfer_posting_pap_facility_feature_ids"><option value="No Required Features">No Required Features</option>
      <option value="13">Pool</option>
      <option value="15">Sauna</option>
      <option value="16">Salon</option>
      <option value="17">Massage</option>
    </select> 
    

    和javascript:

    $('#transfer_posting_pap_facility_feature_ids').select2({
      placeholder: 'Select Feature(s)',
      allowClear: true
    });
    
    $('#transfer_posting_pap_facility_feature_ids').on("select2:selecting", function(e) {
      var selectedFeature = e.params.args.data.text
        console.log(selectedFeature);
      if (selectedFeature === 'No Required Features') {
        $('#transfer_posting_pap_facility_feature_ids').val(null).trigger("change");
    
        $('#transfer_posting_pap_facility_feature_ids').select2({
          placeholder: 'No Required Features'
        });
    
      }
    });
    

    以下是js小提琴的链接:http://jsfiddle.net/mxqc76e8/3/

    如何更新代码以使此方案有效?

1 个答案:

答案 0 :(得分:1)

请查看更新的小提琴代码。 Updated Fiddle
添加了一些条件,代码更改了一点 希望它能帮到你

$('#transfer_posting_pap_facility_feature_ids').select2({
  placeholder: 'Select Feature(s)',
  allowClear: true
});

$('#transfer_posting_pap_facility_feature_ids').on("select2:selecting", function(e) {
    if ($("#transfer_posting_pap_facility_feature_ids option[value='No Required Features']:selected").length > 0){
    alert('No Required Feture is selected');
    exit;
    }
  var selectedFeature = e.params.args.data.text
 if (selectedFeature =='No Required Features') {    
    $('#transfer_posting_pap_facility_feature_ids').select2({
      placeholder: 'No Required Features'
    });
    $('li.select2-selection__choice').remove();
  $('#transfer_posting_pap_facility_feature_ids').val('');
  }
});