How to have the value with existing data in Select2 multiple select - javascript

Here is my script for select2 multiple select box. I am using ajax for fetching the data. I need to add the current selections with existing values.
Ex : If 1000,1001 is already in the list. And if the user types 1002 it should merge with the old result and display as 1000, 1001, 1002.
Here is how i place the values in select2
In php i construct the options
foreach ($zips as $zipcodes) {
$pinLists .= $zipcodes->zipcode_id . ',';
$htmlElements .= '<li class="select2-selection__choice" title=""><span class="select2-selection__choice__remove" role="presentation">×</span>' . $zipcode->zipcode_id . '</li>';
}
Then in html i append to it
var htmlElement = '<?php echo $htmlElement ?>';
$(".firstSelect").append(htmlElement);
I tried like
$(".firstSelect").on('change', function(e) {
$(".firstSelect").append(htmlElement);
});
But i can't able to place the old values on change action.
Here is my entire script of select2 ajax
$("#firstList").select2({
ajax: {
url: "../getZipList",
type: "POST",
contentType: "application/json; charset=utf-8",
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: 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 the remote JSON data
return {
results: data.items
};
//console.log(data.it)
},
cache: true
},
escapeMarkup: function (markup) {
return markup;
}, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
How can i do this. Help pls

Related

how to pass $(this) of select2 inside ajax parameters

I need to pass $(this) of select2 inside ajax to get data-url like like code below it, $(this).data("url") not working.
$(".select-ajax").select2({
allowClear: $(this).data('allowclear') ? $(this).data('allowclear') : false,
ajax: {
url: $(this).data("url"),
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data
};
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
}, // let our custom formatter work
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
The easiest way to deal with this and similar situations is to set a constant to refer to.
const selectAjax = $(".select-ajax");
selectAjax.select2({
allowClear: selectAjax.data('allowclear') ? selectAjax.data('allowclear') : false,
ajax: {
url: selectAjax.data("url"),
dataType: 'json',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function(data) {
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
return {
results: data
};
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
}, // let our custom formatter work
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
You need to set this as a variable.
var that = $(this);
that.select2({
...
//other code
url: $(that).attr("data-url")
//other code
});

Unable to select result from select2 dropdown

I have the following javascript/jQuery that pulls in data from via AJAX. That works fine however I can cannot seem to be able to select an option from the dropdown? Can anyone explain what I have done wrong..
This is something to do with the id..
$(".js-data-example-ajax").select2({
ajax: {
url: "/admin/generator/teams",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
id: function(data){ return data._id; },
});
First you should make sure processResults function returns an array of objects with id and text properties like this:
{ id: '1', text: 'Option 1' }
Then once the options are loaded, you can set the value by calling:
$(".js-data-example-ajax").val('1').trigger('change');

Select2 - start ajax search on enter

I have a Select2 input which I use to search (remote data).
Currently, it works like this:
when user types 1 one more characters we trigger search automatically
Now, the fun part:
I need to add following behaviour:
when user focus on in this input and just hits Enter button, I need to trigger search with one character '*' BUT without actually writing that character in the input.
It should just send search request with character * but input should stay empty.
Is that even possible without messing Select2 code?
My code:
$("#account").select2({
language: "en",
ajax: {
url: window.urls.ajax_account_search,
dataType: 'json',
delay: 500,
data: function(params){
console.log(params);
return {
query: params.term,
page: params.page
}
},
processResults: function(data, params){
return {
results: data.items
}
},
cache: true
},
escapeMarkup: function(m) { return m; },
templateResult: formatSearchResult,
templateSelection: formatSearchSelection,
minimumInputLength: 1
});
Instead of triggering the search on enter (with * being sent), you can just send * when there is no search term present. This also means dropping the minimumInputLength requirement, but that seems to line up with what you are looking for.
$("#account").select2({
language: "en",
ajax: {
url: window.urls.ajax_account_search,
dataType: 'json',
delay: 500,
data: function(params){
return {
query: params.term || '*', // send * if there is no term
page: params.page
}
},
processResults: function(data, params){
return {
results: data.items
}
},
cache: true
},
escapeMarkup: function(m) { return m; },
templateResult: formatSearchResult,
templateSelection: formatSearchSelection
});

Select2 Multi Select Remote s.results is not function

Im develop web apps that have a form.In that's form, i want to make multi select item with remote data (ajax) because i have more than 1800 data.
Im using Select2 for this. But i got an error when try to make it.
Uncaught TypeError: s.results is not a function
This is my init code:
// ----- DIAGNOSE SELECTION ----- //
var res5 = str.replace("antrian", "diagnosa").replace("periksa", "getData");
$("#diagnosa").select2({
placeholder: "Ketik untuk mencari diagnosa pasien...",
minimumInputLength: 3,
multiple: true,
ajax: {
url: res5,
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
var results = [];
// parse the results into the format expected by Select2.
// since we are using custom formatting functions we do not need to
// alter the remote JSON data
$.each(data, function(index, item){
results.push({
id: item.kd_diagnosa,
text: item.nm_diagnosa
});
});
console.log(results);
return {
results: results
};
},
cache: true
}
});
// ----- DIAGNOSE SELECTION ----- //
My select2.js
https://jsfiddle.net/22m3tqbf/
My select2.css
https://jsfiddle.net/fgqontcs/
Please help me. If you need any data, i can provide it. Thanks in advanced

select2 version 4 ajax data : results not appearing in control

Since I have switched to version 4 of the select2 plugin, my ajax calls do not work anymore.
I get a response in the form of an array which prints ok in the console but the results don't show in the select2 control.
http response :
{"results":{"id":"ok","term":"ok","description":"ok"}}
My code :
$(function(){
$('#appbundle_marketplace_product_ingredient_barcode').select2({
minimumInputLength: 3,
ajax:
{
delay: 250,
url: "{{ path('search_barcode') }}",
dataType: 'json',
debug: true,
data: function (params) {
// console.log(params.term);
return {barcode: params.term};},
processResults: function (data) {
console.log(data);
return data;
}
}
});
});
the data printed in the console is the following object :
Object {results: Object}
results: Object
description: "ok"
id: "ok"
term: "ok"
__proto__: Object
__proto__: Object
How can I have the select2 display a result in the dropdown, then click the result to have it selected ?
Thanks a lot,
Great question, same issue I ran into.
I had a similar issue, working in Wordpress. I had to update my php to return this:
// This prepared SQL query returns objects, so I thought I was fine
$partList = $wpdb->get_results( $sql );
// echo json_encode( $partList ); <- worked, but not quite right...
// Select2 wanted an array of items, so I added this
$jsonItems = array("items"=>$partList);
echo json_encode( $jsonItems );
In my JS I have this...
function formatPartSelection(ajaxData){
return ajaxData.commonName || ajaxData.text;
}
function formatAjaxResponse (ajaxData){
if(ajaxData.loading) return ajaxData.text;
var markup = '<div class="clearfix select2-result-selectable" style="border-bottom:solid; border-bottom-color: #D3D3D3">' +
'<div class="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-10"><span style="font-weight: bold;">' + ajaxData.fieldOne + ' | ' + ajaxData.text + '</span></div>' +
'</div>';
if (ajaxData.description) {
markup += '<div class="col-sm-10">' +
'<div class="clearfix">' +
'<div><i>' + ajaxData.description + '</i></div>';
}
markup += '</div><br/></div>';
return markup;
}
$.fn.select2.amd.require(
["select2/core", "select2/utils", "select2/compat/matcher"],
function (Select2, Utils, oldMatcher) {
});
$('.myClass').select2({
placeholder: "Select part(s)...",
minimumInputLength: 3,
multiple: true,
ajax: {
url: url_to_your_php,
delay: 250,
type: "POST",
dataType: 'json',
data: function (params) {
var queryParameters = {
action: 'my_enqued_wp_ajax',
searchStringValue: params.term
}
return queryParameters;
},
processResults: function (data) {
console.log(data);
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
templateResult: formatAjaxResponse,
templateSelection: formatPartSelection
});
The above code allowed me to get the list of items to select from working, but I couldn't actually click any of them. Many hours later, I found this answer which helped me to actually be able to select one of the values in my Select2 dropdown list:
https://stackoverflow.com/a/29082217/4266699
*Note, I had the luxury of creating a column in my DB called ID, so I was able to fix this on the backend.
Hope this helps!

Categories

Resources