BootStrap select2 Dynamic Value Change Method
- 2021-07-18 07:03:56
- OfStack
1. selec2 dynamic assignment
var temp=JSON.stringify({ id: "1| All parking lots ", name: " All parking lots " });
$("#e_pid").attr("value", tempP);
$("#e_pid").select2({
placeholder: " Find the parking lot name ( Multiple choice )",
language: "zh-CN",
minimumInputLength: 1,
allowClear: true,
multiple: true,
ajax: {
// instead of writing the function to execute the request we use Select2's convenient helper
url: "/manage/park/index/json/index",
dataType: 'json',
data: function (term, page) {
return {
parkName: term,// search term
powerpid: "1"
};
},
results: function (data, page) { // parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to alter remote JSON data
for (var i = 0; i < data.length; i++) {
data[i].id = data[i].id+"|"+data[i].name;
};
data.push({ id: "577cb125f8d2c404572413d1| None ", name: " None " });
return {
results: data
};
}
},
initSelection: function (element, callback) {
// Assign initial value
// the input tag has a value attribute preloaded that points to a preselected movie's id
// this function resolves that id attribute to an object that select2 can render
// using its formatResult renderer - that way the movie name is shown preselected
var data = [];
var value = ""
var str = $(element).val().split('^');
for (var i = 0; i < str.length; i++) {
var temp = JSON.parse(str[i]);
value += temp.id + ",";
data.push(temp);
}
;
value = value.substring(0, value.length - 1);
$(element).val(value);
callback(data);
},
formatSelection: function (item) {
return item.name;// Note the name , want to talk to ajax Returns the key value of an array 1 Sample
}, // Select the display in the result
formatResult: function (item) {
return item.name;// Note the name
},// Display in Search List
dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
escapeMarkup: function (m) {
return m;
}
});
2. Dynamic change value
$("#e_pid").attr("value", temp);
$("#e_pid").trigger('change'); // After changing the value dynamically, the change time must be triggered. Otherwise, it will not take effect