事件后,select2插件从选项列表中删除项目

时间:2017-12-14 07:55:52

标签: javascript jquery jquery-select2

我使用 selec2 plugin ,我想从主选项列表中删除一个选项。当我点击" x"按此代码按钮,它只从插件列表中删除。关闭/打开后它恢复。

任何人都可以帮助我吗?

jsfiddle

HTML:

<select id="select">
    <option value="Provider 1">Provider 1</option>
    <option value="Provider 2">Provider 2</option>
    <option value="Provider 3">Provider 3</option>
    <option value="Provider 4">Provider 4</option>
    <option value="Provider 5">Provider 5</option>
</select>   

JS:

function format(state) {
  if (state.id == null) {
    return state.text;
  }

  var $option = $("<span></span>");
  var $preview = $('<span class="select2-item-remove">×</span>');
  $preview.on('mouseup', function (e) {
    e.stopPropagation();
  });

  $preview.on('click', function (e) {
    $(this).closest('li').remove();
  });

  $option.text(state.text);
  $option.append($preview);

  return $option;
}

$("#select").select2({
  templateResult: format,
  escapeMarkup: function (m) { return m; }
});

1 个答案:

答案 0 :(得分:2)

您还必须删除选项元素。

所以这是你的小提琴更新:

https://jsfiddle.net/beaver71/0wz9m7gz/

&#13;
&#13;
$(document).ready(function () {
  function format(state) {
    if (state.id == null) {
      return state.text;
    }

    var $option = $("<span></span>");
    var $preview = $('<span data-opt="'+state.element.id+'" class="select2-item-remove">×</span>');
    $preview.on('mouseup', function (e) {
      e.stopPropagation();
    });

    $preview.on('click', function (e) {
      $(this).closest('li').remove();
      var opt = $(this).data('opt');
      $("#"+opt).remove();
    });

    $option.text(state.text);
    $option.append($preview);

    return $option;
  }

  $("#select").select2({
    templateResult: format,
    escapeMarkup: function (m) { return m; }
  });
});
&#13;
.select2-results__option {
  position: relative;
}
.select2-item-remove {
  position: absolute;
  right: 9px;
  top: 5px;
  z-index: 1100;
  z-index: 9999;
  cursor: default;
  display: block;
  font-weight: bold;
  font-size: 15px;
  padding: 0 2px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.full.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.css" rel="stylesheet"/>

<select id="select" multiple="multiple" style='width:300px'>
  <option id="opt1" value="Provider 1">Provider 1</option>
  <option id="opt2" value="Provider 2">Provider 2</option>
  <option id="opt3" value="Provider 3">Provider 3</option>
  <option id="opt4" value="Provider 4">Provider 4</option>
  <option id="opt5" value="Provider 5">Provider 5</option>
</select>
&#13;
&#13;
&#13;