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');
}
Related
What could be wrong in the code below?
I'm using Select2 version 4, when there's no result the No result dropdown shows,
But when there's result nothing shows (The dropdown does not show).
function formatProduct(product) {
if (product.loading) return product.text;
var markup = '<div class="product-to-compare" data=' + product.id + '>' + product.text + '</div>' ;
return markup;
}
function formatProductSelection(product) {
return product.name || product.text;
}
$(".select-category").select2({
ajax: {
url: "/autocomplete",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatProduct,
templateSelection: formatProductSelection
});
In the result from php script I have something like this:
{"items":{"id":12,"text":"Sport"}}
But the dropdown does not show, is there something wrong I'm doing?
I am using Select2 with remote data. when i click on drop-down. no option will shows until write in search box.
But i want to show some data when drop-down open.
I am trying it with initselection or data but its initialize when data present in selected value.
$('.countrySelection').select2({
placeholder: "Select Country",
allowClear: true,
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: base_url+'ajax_response/getCountry',
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) {
$(".statenoSelect").select2("val", "");
$(".citynoSelect").select2("val", "");
var more = (page * 2) < data.page
return {
results: data.items,
more: more
};
},
cache: true
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax(base_url+'ajax_response/getCountry?id=' + id, {
dataType: "json"
}).done(function(data) { callback(data['items'][0]); });
}else{
$.ajax(base_url+'ajax_response/getCountry?default=true', {
dataType: "json"
}).done(function(data) { callback(data['items']); });
}
},
data:function(element, callback) {
callback(JSON.parse($(element).attr('data-selection')));
},
formatResult: repoFormatResult,
formatSelection: repoFormatResult,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
}).focus(function () { $(this).select2('open'); });
Its working with ajax, but how can I add options without search anything
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');
I am trying to use select2 pulling data using ajax from php back end. I could not figure out the documentation as much as I would like to. I think i probably missed some taken for granted stuffs. Please can you help with a simple example. I started or like this...
html
<select id="select_proj" style="width:10em">
<option value="" selected="selected">Search</option>
</select>
js
$('select').select2();
$("#select_proj").select2({
ajax: {
url: '../app/select_prj.php',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
select_proj: term, // search term
page: 10
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
In php
$data_wildcardsearch = $_POST['term'];
is throwing error
[Notice: Undefined index: term in b>-----/app/select_prj.php on line 18]
Could you please help? Can you please share a sample code as well?
In data() function you must pass 'term' as a key instead of select_proj.
$('select').select2();
$("#select_proj").select2({
ajax: {
url: '../app/select_prj.php',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
term: term, // search term
page: 10
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
Then you can get it by:
$data_wildcardsearch = $_POST['term'];
You have post term with key => 'select_proj'.
Change code as below,
$data_wildcardsearch = $_POST['select_proj'];
OR
data: {term: term, page: 10},
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"
}
});