[英]Cannot get selected value of Select2 dropdownlist
我在MVC項目中使用Select2 Dropdown下拉列表,如下所示。 盡管我可以通過直接設置AJAX來傳遞“ query”參數,但無法在下面的數據部分中獲取所選文本或dropdownlist的值。 如何獲得?
@Html.DropDownListFor(x => x.StudentId, Enumerable.Empty<SelectListItem>(),
new { style ="width: 100%;" } )
$("#StudentId").select2({
multiple: false,
placeholder: "Select",
allowClear: true,
tags: true,
ajax: {
url: '/Grade/StudentLookup',
dataType: 'json',
delay: 250,
data: function (params) {
return {
//q: params.Name, // search term
//page: params.page
query : 'test' //this parameter can be passed via AJAX
//!!! but I cannot get the selected text or value of dropdownlist
};
},
processResults: function (data, page) {
var newData = [];
$.each(data, function (index, item) {
newData.push({
id: item.Id, //id part present in data
text: item.Name //string to be displayed
});
});
return { results: newData };
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 0, //for listing all, set : 0
maximumInputLength: 20, // only allow terms up to 20 characters long
});
您可以簡單地偵聽select2:select
事件以獲取所選項目。
select2:選擇
每當選擇結果時觸發。
var select2 = $(".select2"); select2.select2({ multiple: false, placeholder: "Select", allowClear: true, tags: true, width: "180" }); function onSelect(evt) { console.log($(this).val()); } select2.on('select2:select', onSelect)
@import url('https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css');
<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.3/js/select2.min.js"></script> <select class="select2"> <option value="item-1">Item 1</option> <option value="item-2">Item 2</option> <option value="item-3">Item 3</option> <option value="item-4">Item 4</option> <option value="item-5">Item 5</option> <option value="item-6">Item 6</option> <option value="item-7">Item 7</option> <option value="item-8">Item 8</option> <option value="item-9">Item 9</option> <option value="item-10">Item 10</option> </select>
============================已解決=================== ===========
這是問題的解決方案:
為了通過AJAX在Select2中發送文本值,請在數據部分中使用params.term ,如下所示。 非常感謝@DavidDomain作為回答,它對於使用選定的索引更改也非常有用。
//code omitted for brevity
data: function (params) {
return {
query: params.term, // search term
page: params.page
};
},
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.