Select2 is one of the best libraries to add in the sections where to need a textbox autocomplete options. Many entry level developers feel easy to do static autocomplete feature but they feel difficult to add dynamic values in select box.
Select2 dynamic autocompete |
Here we are going to give code to get get dynamic values in the select2 selectbox based on the input given in select2 textbox.
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"></link>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script>
$("#select_box_id").select2({
ajax: {
url: "server page link",
dataType: 'json',
delay: 250,
data: function (params) {
return {
campaign_name: params.term, // search term
};
},
processResults: function (data, params) {
var values = [];
$.each(data, function (key, val) {
if(val._id != '')
{
values.push({
id: val.id,
text: val.campaign_name
});
}
});
// Sample json data -> [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }]
return {
results: values, //appending values from server to options tag
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2,
});
</script>
If you have any doubts, feel free to share below.. We will respond as soon as possible.
No comments:
Post a Comment