InitSelection not work in Select2 4.0.3 js - javascript

I am using select2, everithing working fine but default selection not work,
I am using select2 4.0.3 js
I am using initSelection, but its display like this screenshot,
var data = <?php echo $cat_json; ?>;
function templateResult(node) {
var $result = $('<span style="padding-left:' + (20 * node.level) + 'px;">' + node.text + '</span>');
return $result;
};
function formatSelection(node) {
return node.sel_text;
};
$("#mySelect").select2({
initSelection: function (element, callback) {
var file_id = 29;
$.ajax({
url: "/admin/folders/get_selected_cat/" + file_id,
dataType: "json",
}).done(function (data) {
console.log(data); //Object {id: "1", text: "Product"}
callback(data.text);
});
},
placeholder: 'Select an option',
width: "600px",
tags: true,
data: data,
templateSelection: formatSelection,
templateResult: templateResult,
});
can you please help me to fix this?
thanks

You have to trigger selected value
var selected = [{id: "20"}];
var data = <?php echo $cat_json; ?>;
function templateResult(node) {
var $result = $('<span style="padding-left:' + (20 * node.level) + 'px;">' + node.text + '</span>');
return $result;
}
;
function formatSelection(node) {
return node.sel_text;
}
;
$("#mySelect").select2({
placeholder: 'Select an option',
width: "600px",
tags: true,
data: data,
templateSelection: formatSelection,
templateResult: templateResult,
});
$('#mySelect').val(selected).trigger('change');
I hope this code will work.

After many tests, for version 4.0.3 this trick worked
initSelection: function (element, callback)
{
var id = $(element).val();
if (id !== "" && id !== 0)
{
$.ajax(url,
{
data: {q: id},
dataType: "json"
}).done(function (data)
{
$.each(data, function (i, value)
{
input.append('<option value='+value[0].id+' selected>'+value[0].text+'</option>');
callback({id: value[0].id,text: value[0].text});
});
;
});
}
}

This works well for me.. :)
initSelection: function (element, callback)
{
var id = $(element).val();
if (id !== "" && id !== 0)
{
$.ajax("/visits/exam/findings/selected?visit_id=" + $('#visit_id').val(),
{
data: {q: id},
dataType: "json"
}).done(function (data)
{
$.each(data, function (i, value)
{
$("#basic_exam_findings").append('<option value='+value['id']+' selected>'+value['text']+'</option>');
callback({id: value['id'],text: value['text']});
});
;
});
}
}

Related

Bootstrap Select2 doesn't firing select event on paste until type any word

I use bootstrap select2 v4.* on my site (Yii 2.x) and have met a problem:
The event select2:select doesn't firing on text paste with ctrl+v until I type any text. After typing - it works fine. What i'm doing wrong?
JS:
function formatResult(data) {
var content = '<span>' + data.id + '\t' + data.text + '</span>';
return $(content);
};
function formatSelection(data) {
var content = '<span>' + data.id + '</span>';
return $(content);
}
$('#wiz-asin-search').select2({
tags: true,
minimumInputLength: 3,
placeholder: 'specify asin..',
ajax: {
url: '/keyword-tracker/get-mwslisting-asins',
method: 'GET',
dataType: 'json',
data: function (params) {
return {
searchAsin: params.term
}
},
results: function (data) {
return { results: data.results };
}
},
templateResult: formatResult,
templateSelection: formatSelection,
escapeMarkup: function(m) { return m; }
}).on('select2:select', function(){
var asin = $(this).val();
console.log('asinSearch.change fired: ' + asin);
validationHighLight(false);
validateAsin(asin);
});
The solution is:
initialize select2 with some data.
$('#wiz-asin-search').select2({
// allowClear: true,
tags: true,
minimumInputLength: 3,
data: [
{
id: ' ',
text: 'testAsin'
}
],
...
and it will work fine.
You simply use this code:
$('#yourElement').select2();
Had a similar issue and resolved it using the createTag callback.
$('select').select2({
createTag: function (params) {
var term = $.trim(params.term);
if (term === '') {
return null;
}
if (this.$element.find('option').length === 0) {
this.$element.append($('<option data-select2-tag="true">'));
}
return {
id: term,
text: term
}
}
});

Want to prevent selecting specific item in jQuery UI AutoComplete

I am developing textbox with autocomplete using jQuery UI Autocomplete.
After that, I can create textbox with autocomplete, but one issuce has occured now.
In my textbox, I want to prevent selecting specific item from autocomplete list.
If I select specific item, Autocomplete list display again or not to close.
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
});
});
});
If someone know answer, please teach me.
Based on the example from here: How to disable element in jQuery autocomplete list
I think this code will work for you:
$(function (prefixText) {
$("textBox").autocomplete({
autoFocus: false,
minLength: 0,
delay: 50,
source: function (request, response) {
var data = "{ 'prefixText': '" + prefixText
+ "','count': '" + 30
+ "','pixWidth': '" + 100 + "' }";
$.ajax({
type: "POST",
url: "Example.asmx/" + method,
cache: false,
data: data,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.name,
id: item.id,
name: item.name
}
}))
}
});
},
select: function (event, ui) {
var id = ui.item.id
//not match guid type
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
if ($("text_id") !== null) {
$("text_id").val(-1);
}
return false
}
else {
if ($("text_id") !== null) {
$("text_id").val(ui.item.id);
}
$("textBox").val(ui.item.name);
}
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
//Add the .ui-state-disabled class and don't wrap in <a> if value is empty
var id = item.id
if (id.match(/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}/) === null) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else{
return $("<li>")
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
};
});
If you can provide a working version of your code (the items can also be from a predefined list, not based on ajax call) it will be much easier to help.

Loop thru JSON response and return to Jquery

I'm almost there and on my first jquery autocomplete script... I just need some help to figure out how to return the founded elements has link so that we can click on them.
Here a part of my js code:
$(document).ready(function() {
var attr = $('#leseulsteve_lieuxbundle_lieutype_nom').attr('data-url');
var searchRequest = null;
$("#leseulsteve_lieuxbundle_lieutype_nom").autocomplete({
minLength: 3,
source: function(request, response) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: attr,
method: 'get',
dataType: "json",
data: {nom: request.term},
success: function(data) {
searchRequest = null;
console.log(data);
$.each(data, function (i, v) {
--- SOME VARIABLE I GUESS TO STORE THE RESULT ---
});
return THE 'SOME VARIABLE;
}
}).fail(function() {
searchRequest = null;
});
}
});
});
In the console I got this from the console.log(data) line:
Object {École secondaire De Rochebelle: "/GestigrisC/app_dev.php/lieux/voir/2", École secondaire la Camaradière: "/GestigrisC/app_dev.php/lieux/voir/3"}
I have control over how the JSON feed is built, so no worries there if it's helps to build that super mysterious for me now variable to return.
Thanks a lot for the help!
If you just want to build links and put them into your HTML then I think you're looking for something like this:
success: function(data) {
var html = '';
$.each(data, function (i, v) {
html += ''+i+'';
});
$('#container_id').html(html);
}
Got it right, thanks for your help :)
$(document).ready(function() {
var attr = $('#leseulsteve_lieuxbundle_lieutype_nom').attr('data-url');
var searchRequest = null;
$("#leseulsteve_lieuxbundle_lieutype_nom").autocomplete({
minLength: 3,
source: function(requete, reponse) {
if (searchRequest !== null) {
searchRequest.abort();
}
searchRequest = $.ajax({
url: attr,
method: 'get',
dataType: "json",
data: {nom: requete.term},
success : function(donnee){
reponse($.map(donnee, function(objet){
return {label: objet.type + ' | ' + objet.label, type: objet.type, id: objet.id};
}));
}
}).fail(function() {
searchRequest = null;
});
},
select: function (event, ui) {
$('#leseulsteve_lieuxbundle_lieutype_nom').val(ui.item.label);
$('#leseulsteve_lieuxbundle_lieutype_type').val(ui.item.type);
$('#leseulsteve_lieuxbundle_lieutype_id').val(ui.item.id);
$('#formulaire').submit();
}
});
});

jQuery autocomplete with multiple items not working

I am working on jQuery autocomplete which as two items in a <ul>.
I am getting json item from $.getJSON function and the json object looks like :
[{
"merchant_name": "Myntra",
"merchant_details": "Flat Rs.225 Cashback"
}, {
"merchant_name": "Adlabs imagica",
"merchant_details": "Rs 170 per sale"
}, {
"merchant_name": "godaam",
"merchant_details": "Rs 140 per sale"
}, {
"merchant_name": "Homeshop18",
"merchant_details": "Upto 8% Cashback"
}]
My function looks as follows:
$('#search_bar').keyup(function(e) {
var searched = $('#search_bar').val()
$.getJSON('<?php echo base_url();?>get_data', 'title=' + searched, function(result) {
var elements = [];
$.each(result, function(i, val) {
elements.push({
'merchant_name': val.merchant_name,
'merchant_details': val.merchant_details
})
}) $('#search_bar').autocomplete({
delay: 0,
source: elements,
select: function(event, ui) {
$("input#search_bar").val(ui.item.merchant_name + " / " + ui.item.merchant_details);
$("#get").click();
}.data("autocomplete")._renderItem = function(ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a><strong>" + item.merchant_name + "</strong> / " + item.merchant_details + "</a>").appendTo(ul);
};
})
})
});
I am not able to proceed forward.
Please help me to solve this one.
I wrote this for one of my projects and it works perfectly. I'm not sure why you are detecting keyup when autocomplete does that for you... But this snippet should give you all the functionality you need.
$("#edit_profile .location").autocomplete({
source: function(request, response) {
$.ajax({
url: BASE_URL + "lib/ajax.php",
type: "GET",
data: "autocomplete_location=1&term=" + request.term,
cache: false,
success: function(resp) {
try {
json = $.parseJSON(resp);
} catch (error) {
json = null;
}
//
if (json && json.status == "OK") {
//
response($.map(json.predictions, function(item) {
return {
label: item.description,
value: item.description
}
}));
//
}
}
});
},
minLength: 1,
change: function (event, ui) {
if (!ui.item){
$(this).val("");
}
}
});

Select2 allowClear not working with dynamic dropdown list

I have tried a lot of ways to fix this problem.
At a dynamic list loaded via ajax, I can't make allowClear work.
Here is my jsFiddle
HTML:
<select id="first" class="init-select2" data-placeholder="First dropdown" data-allowclear="true">
<option></option>
<option>First option</option>
<option>Second option</option>
</select>
<select id="second" class="init-select2" data-placeholder="Second Dropdown" data-allowclear="true" disabled="disabled">
<option></option>
</select>
Javascript:
$(function() {
$('.init-select2').removeClass('init-select2').each(function(){
if ($(this).attr("data-allowclear") && $(this).attr("data-allowclear") == "true"){
$(this).select2({
allowClear: true
});
} else if ($(this).attr("data-allowclear") && $(this).attr("data-allowclear") == "false") {
$(this).select2({
allowClear: false
});
}
});
$('#first').change(function () {
var options = [];
$.ajax({
type: "POST",
url: "/echo/json/",
data: {"json":JSON.stringify({"one":"first","two":"second","three":"third"})},
cache: false,
success: function(data) {
$.each(data, function (index, value) {
options.push("<option>" + value + "</option>");
$("#second").find('option').remove().end().append(options).attr("disabled", false).select2({ allowClear: true });
});
}
});
});
});
in jsfiddle are already added the select2 javascript and css, please have a look there
Fixed by adding an "<option></option>" to second dropdown each time I change the value of first dropdown. See success handler below:
$('#first').change(function () {
var options = [];
$.ajax({
type: "POST",
url: "/echo/json/",
data: {
"json": JSON.stringify({
"one": "first",
"two": "second",
"three": "third"
})
},
cache: false,
success: function (data) {
options.push("<option></option>");
$.each(data, function (index, value) {
options.push("<option>" + value + "</option>");
$("#second").find('option').remove().end().append(options).attr("disabled", false).select2({
allowClear: true
});
});
}
});
});
Example of one of my own, as you can see I don't use "option" tags within my loop.
function companyURL() {
if ($.isNumeric($('#supplier_select').val())) {
return company_url + '/' + $('#supplier_select').val() + '/';
} else {
return company_url;
}
}
var results = [];
$('.company_select').select2({
ajax: {
url: function () {
return companyURL();
},
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
results = [];
results.push({
id: '',
text: 'Select a company'
});
$.each(data, function (index, item) {
results.push({
id: item.company_id,
text: item.company_name
});
});
return {
results: results
};
}
}
});

Categories

Resources