【问题标题】:Clear select2 multiple when specified value is selected选择指定值时清除 select2 倍数
【发布时间】:2017-05-17 11:33:01
【问题描述】:

我尝试在 select2 多选中实现以下场景。

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

这是我的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 fiddle 的链接:http://jsfiddle.net/mxqc76e8/3/

我应该如何更新我的代码以使这种情况有效?

【问题讨论】:

  • 很抱歉,但无法理解您真正想要什么。你能描述得更详细些吗
  • @ankitverma:当用户在我的 jsfiddle 中的选择中选择“无必需功能”时,我想清理选择,因此它将为空。

标签: javascript jquery jquery-select2


【解决方案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('');
  }
});

【讨论】:

  • 还是不行。我选择“Pool”,然后选择“No Required Features”并选择仍然包含值。选择“无必需功能”后应为空
  • 当我使用“无必需功能”时,它会在浏览器控制台中引发错误:ReferenceError: exit is not defined
  • jsfiddle.net/akit/mxqc76e8/6检查这个小提琴,我已经用return语句替换了exit
猜你喜欢
  • 2020-04-07
  • 2018-05-29
  • 2014-12-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-02
  • 2014-11-24
  • 1970-01-01
相关资源
最近更新 更多