I have a webpage that requires to use select2 component. It is required to show selected values on load as well. In my JS file I have two constructs
JS - Construct 1 for choose/remove options
$("#inp_select_linkproject").select2({
minimumInputLength: 2,
maximumSelectionLength: 1,
ajax: {
type : 'POST',
url: '../../ase.php',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
wildcardsearch: term, // search term
data_limit: 10,
data_offset: 0,
page_mode:"SELECT",
agent_id:$("#ipn_hdn_userid").val()
};
},
processResults: function (data, page) {
return { results: data.dataset};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
});
JS - Construct 2 for catering onload
$.fn.getCurrentSelect2data = function(){
$("#inp_select_linkproject").val(null).trigger("change");
var $element = $('inp_select_linkproject').select2(); // the select element you are working with
var postFormData = {
'eucprid' : $("#ipn_hdn_eucprid").val()
};
var $request = $.ajax({
type : 'POST',
url: '../../ase_x.php',
data : postFormData,
dataType: 'json'
});
$request.then(function (data) {
// This assumes that the data comes back as an array of data objects
// The idea is that you are using the same callback as the old `initSelection`
console.log("rowselect,data0-"+data[0].text);
for (i=0; i<data.length; i++) {
$('#inp_select_linkproject').append($("<option/>", {
value: data[i].id,
text: data[i].text,
selected: true
}));
}
$('#inp_select_linkproject').trigger('change');
});
}
Now the issue is that repetition of selection is happening and the number of repetition increases on choosing more options. Could you please help me out here?
The issue you are hitting is not specific to Select2, if you remove the calls to Select2 from your code you will see it happens to a standard <select> as well. The problem is that you are not clearing out old selections before you register the new selections, so they are just getting appended to the end (and causing duplicates).
You can fix this by calling
$select.empty();
Right before you start appending new options to your $select. In your case, that would mean changing your callback to
// clear out existing selections
$('#inp_select_linkproject').empty();
// add the selected options
for (i=0; i<data.length; i++) {
$('#inp_select_linkproject').append($("<option/>", {
value: data[i].id,
text: data[i].text,
selected: true
}));
}
// tell select2 to update the visible selections
$('#inp_select_linkproject').trigger('change');
Related
My script won't load any data in the Select2. I made a test.php with JSON data (which will be provided external after everything works. (test.php is my internal test)).
Output of test.php
[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]
jQuery script:
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
alert(data);
},
processResults: function(data) {
return {
results: $.map(data.suggestions, function(obj) {
return {
id: obj.key, text: obj.value
}
})
};
}
}
});
I have been searching and checking all other solutions. It it not working for me. I'm stuck.
Update: jQuery script so far
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
placeholder: "Voer uw postcode in..",
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
return {
ajax_call: 'addressZipcodeCheck_BE',
zipcode: '1200'
};
},
processResults: function(data) {
alert(data);
correctedData = JSON.parse(data)[0]suggestions;
alert(correctedData);
return {
results: $.map(correctedData, function(obj) {
return {
id: obj.key,
text: obj.value
}
})
};
}
}
});
Here is a working fiddle for your example.
I have done if on a local JSON object but you can replicate the same results on your response or maybe change your response accordingly.
Your data.suggestions is nothing. Because data is a JSON array whose first element is a JSON object with key suggestions and value an array of suggestions.
Run this code in your JQuery enabled browser console and you will undestand.
var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;
Also check this answer to see how a proper response should look like.
Updated answer:
Sending additional data to back-end:
$('#billing_postcode_gemeente').DataTable(
{
......
"processing" : true,
"serverSide" : true,
"ajax" : {
url : url,
dataType : 'json',
cache : false,
type : 'GET',
data : function(d) {
// Retrieve dynamic parameters
var dt_params = $('#billing_postcode_gemeente').data(
'dt_params');
// Add dynamic parameters to the data object sent to the server
if (dt_params) {
$.extend(d, dt_params);
}
}
},
});
Here dt_params is your additional parameter (the zipcode
that you wish to send to the server to get an appropriate response). This dt_params gets added to the datatable parameters and can be accessed in your back-end to appropriate the response.
There must be a place where you are taking the zipcode entry. On the listener of that input box you can add the below code to destroy and recreate the datatable to reflect the changes. This code will add key-value (key being zip_code) pair to the dt_params key in your request JSON:
function filterDatatableByZipCode() {
$('#billing_postcode_gemeente').data('dt_params', {
ajax_call: 'addressZipcodeCheck_BE',
zip_code : $('#some_imput_box').val()
});
$('#billing_postcode_gemeente').DataTable().destroy();
initDatatable();
}
Try this way
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
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 data.items;
},
cache: true
},
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
I am using Bootstrap Typeahead (version: v2.0.0). I have result set through an ajax call and would like to show autocomplete list using value and one more attribute.
I have result set like:
{"res":[{"id":617,"value":"DESC: Admin responder comment","user_id":37,"status":1,"comment":"Hi {firstname},\n\nThis is testing.","firstname":"Tom's"},
{"id":625,"value":"DESC: my comment","user_id":37,"status":1,"comment":"Hi {first_name}, anther testing comment","firstname":"William's"}
]}
Autocomplete matching keyword with value attribute and populating it. But, I would like to match keyword with comment attribute as well.
I have tried matcher of typeahead and some solutions mentioned on SO as well but did not found useful. Tried one here: but getting error of "TypeError: Bloodhound is undefined" with that solution.
Please check code below used for autocomplete using result by ajax.
var typeahead_pre_written_xhr = null;
var search_keyword = function ( tid, txtElmt )
{
$( "#typeahead-input" ).typeahead({
items: 20,
source: function(typeahead, query) {
action_url = _base_url + "search/search_keyword/";
typeahead_pre_written_xhr = $.ajax({
cache: false,
type: "POST",
dataType: "json",
url: action_url + query,
data: { 'type': type },
error: function (request, status, error) { },
success: function(data) {
if( typeof data.res != 'undefined' && data.res != '' ) {
typeahead.process(data.res);
}
}
});
},
onselect: function() {
// Do stuff
}
});
};
Please help me to achieve this.
Is it possible to programmatically select an entry for a select2 that uses AJAX for its list build, using the entry's id?
I am using a select2 element in my page to get client information. The select2 uses AJAX to load the list of client names based on the user typing an input.
Once the user selects the client, I post to back end with client_id and run a search / generate a list of data, which is then loaded onto a new impression of the same page.
I want to pre-select the select2 with this client_id and have it show the relevant client_name. How do I get the AJAX based select2 to select this client_id?
My JS and select2 code is:
var resultsArray;
var clientSearch = '{!! $clientSearch !!}';
$(document).ready(function() {
$('#client_id').select2({
theme: 'bootstrap',
placeholder: 'Select client',
val: clientSearch, // TRIED THIS BUT IT DOES NOT WORK
ajax: {
url: '{!! route('client.selectList') !!}',
type: 'POST',
dataType: 'json',
delay: 500,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
resultsArray = data;
params.page = params.page || 1;
return {
results: $.map(data, function(obj) {
return {
id: obj.id, text: obj.client_name + ' (' + obj.state + ' ' + obj.postcode + ')'};
}),
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2
});
});
I have tried setting the val: (per above) and setting the select2 value like below without success:
if (clientSearch != null) {
$('#client_id').select2({'val': clientSearch});
}
if (clientSearch != null) {
$('#client_id').val(clientSearch).trigger("change");
}
if (clientSearch != null) {
$("#client_id").select2('data', {id: clientSearch, text: clientName});
}
I also tried another suggestion such as adding this to the select2 declaration as follows:
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2
}).val(clientSearch).trigger('change');
Thanks for any suggestions
I got the answer from here.
if (clientSearch != null) {
$('#client_id').append('<option value="' + clientSearch + '">' + clientName + '</option>');
$('#client_id').val($('#client_id').val()).trigger('change');
}
I'm using Select2 to populate a dropdown of UK Towns. As the UK Towns DB is huge I figured an AJAX call would be the best way to bring in the data.
I have built a post function and some PHP (In Codeigniter) to catch the query and parse it.
I can see the data is being posted and responded, But my Select2 is not populating with the data.
My jQuery for this is :
$("#areas").select2(
{
tags: [],
ajax: {
url: '/profile/get-towns',
dataType: 'json',
type: "POST",
quietMillis: 100,
data: function (term) {
return {
query: term
};
},
results: function (data) {
return {
results: data.town_id
}
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 4,
placeholder : "Start typing your Town / City",
maximumSelectionSize: 2
}
);
My response jSON (Example) is as follows :
[{"town_id":"16994","town":"Hartle"},{"town_id":"16995","town":"Hartlebury"},{"town_id":"16996","town"
:"Hartlebury"},{"town_id":"16997","town":"Hartlebury Common"},{"town_id":"16998","town":"Hartlepool"
},{"town_id":"16999","town":"Hartley"},{"town_id":"17000","town":"Hartley"},{"town_id":"17001","town"
:"Hartley"},{"town_id":"17002","town":"Hartley"},{"town_id":"17003","town":"Hartley Green"},{"town_id"
:"17004","town":"Hartley Green"},{"town_id":"17005","town":"Hartley Mauditt"},{"town_id":"17006","town"
:"Hartley Wespall"},{"town_id":"17007","town":"Hartley Wintney"},{"town_id":"27051","town":"New Hartley"
},{"town_id":"35891","town":"Stowe-by-Chartley"}]
Where am I going wrong? I would ideally like the select dropdown to have the select value = town_id and the select option to be the town name.
Thank You.
in your select2 configuration:
results: function (data) {
var res = [];
for(var i = 0 ; i < data.length; i++) {
res.push({id:data[i].town_id, text:data[i].town});
}
return {
results: res
}
},
becasue select2 wants the results as array of object with keys id and text.
Otherwise you could already returns a well formed object
[
{"id":"16994","text":"Hartle"},
{"id":"16995","text":"Hartlebury"},
{"id":"16996","text":"Hartlebury"},
{"id":"16997","text":"Hartlebury Common"}
]
then
results: function (data) {
return {
results: data
}
},
On your ajax call, try adding success. Something like this:
success: function( json ) {
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
)};
}
So i have a select2 ajax selector that works perfectly when not using multiple , but when I use multiple it basically sometimes it works , others it doesn't.
$('#organizations').select2(
{
placeholder: "Add Organizations!",
minimumInputLength: 3,
multiple: true,
ajax: {
url: "https://boilerprojects.com/organizations/search",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term, // search term
page_limit: 10
};
},
results: function (data, page)
{
var more = (page * 10) < data.total;
console.log(data.results);
return { results: data.results, more: more };
},
dropdownCssClass: "bigdrop"
},
});
what returns from my PHP is : {"results":[{"id":"6","text":"LukePOLO"}]}
So im getting results its just not populating.
Anyone have any ideas?
If you want to use that infinite scroll option, then your response is wrong.
{"results":[{"id":"6","text":"LukePOLO"}]}
should be something like:
{"results":[{"id":"6","text":"LukePOLO"}], "total":"1"} //Total 1 result
you have key results but do not have a key for total. And in your post data function you should allso say witch page you search.
$('#organizations').select2(
{
placeholder: "Add Organizations!",
minimumInputLength: 3,
multiple: true,
ajax: {
url: "https://boilerprojects.com/organizations/search",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page //you need to send page number or your script do not know witch results to skip
};
},
results: function (data, page)
{
var more = (page * 10) < data.total;
return { results: data.results, more: more };
},
dropdownCssClass: "bigdrop"
}
});