簡體   English   中英

在更改時從select2 multiselect中刪除所選選項。

[英]Remove selected option from select2 multiselect on change.

我有以下代碼。 目的是將帶有文本框的select2框設置為搜索框。 所以我把它實現為多選,但我只想選擇一個選項。

一種選擇是限制使用maximumSelectionLength: 1 但在這種情況下,將顯示限制消息,我不希望發生。 (即使我隱藏它也會占用一些空間)。

其他選項是隱藏除了last-child之外的所有內容,在這種情況下,在提交表單時會將多個值發送到后端。

那么有多種方法可以在multiselect中選擇新值時刪除當前選定的值?

我正在使用select2版本3.5.2

 $('#placeSelect').select2({ width: '100%', allowClear: true, multiple: true, placeholder: "Click here and start typing to search.", data: [ { id: 1, text: "Honolulu" }, { id: 2, text: "Tokyo" }, { id: 3, text: "Delhi" }, { id: 4, text: "Zurich" } ] }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script> <link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/> <h3>Select a value</h3> <input type="text" id="placeSelect"/> 

您只能保留最后選擇的項目並刪除所有其他項目。 像這樣:

 $('#placeSelect').click(function () { var t = $("#placeSelect").val().substr($("#placeSelect").val().length - 1); $("#placeSelect").val(t).trigger("change"); }); $('#placeSelect').select2({ width: '100%', allowClear: true, multiple: true, placeholder: "Click here and start typing to search.", data: [ { id: 1, text: "Honolulu" }, { id: 2, text: "Tokyo" }, { id: 3, text: "Delhi" }, { id: 4, text: "Zurich" } ] }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script> <link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/> <h3>Select a value</h3> <input type="text" id="placeSelect"/> 

 $('#placeSelect').select2({ width: '100%', allowClear: true, multiple: false, placeholder: "Click here and start typing to search.", data: [ { id: 1, text: "Honolulu" }, { id: 2, text: "Tokyo" }, { id: 3, text: "Delhi" }, { id: 4, text: "Zurich" } ] }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="http://cdn.jsdelivr.net/select2/3.4.8/select2.js"></script> <link href="http://cdn.jsdelivr.net/select2/3.4.8/select2.css" rel="stylesheet"/> <h3>Select a value</h3> <input type="text" id="placeSelect"/> 

您正在使用多選項選擇,我建議您執行以下操作:

multiple: false,

只需在查詢中添加以下代碼,它就可以根據需要運行

$('ul.select2-choices').on("click", function() {
    $("ul.select2-choices li .select2-search-choice-close").click();
  });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM