Select2 allowClear not working with dynamic dropdown list - javascript

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
};
}
}
});

Related

How the dependency drop will work during onload with JQuery

There is some data inside a table
When I press the edit button, I can edit all the data for that row.Menu Category and Menu These two data came from Dependent dropdown.
with this code the dropdown in the menu was supposed to show when the menu categories were selected.
modal.find('.modal-body #menu_category_update').val(menu_item_category_selected);
modal.find('.modal-body #menu_update').val(menu_item_selected);
This code goes through the menu category ID and selects Fastfood Dropdown.
$(document).ready(function () {
$(document).on('change','#menu_category_update',function(){
$("#menu_update").empty();
var ddl_menu1 = GetLoadApptUpdate($(this).val());
$("menu_update").empty();
$('#menu_update').select2({
placeholder: "--Select Menu--",
data: ddl_menu1,
dropdownParent: $(this).parent()
});
});
});
function GetLoadApptUpdate(id) {
var b = [];
$.ajax({
type: "GET",
dataType: "json",
cache: true,
async: false,
url: "/admin/menu/item/entry1/"+id,
success: function (response) {
b = response;
},
error: function (response) {
b = { id: 0, text: "No Data" }
}
});
return b;
};
#menu_category_update The function that is being called with this ID is working properly. But my problem is that when I click on the edit button, a dropdown is selected by default, for which the dependent dropdown is not selected.
Expected answer:
Here is the solution:
$('#menu_category_update').val(menu_item_category_selected);
modal.find('.modal-body #menu_update').val(menu_item_selected);
var menu_category_update_val = $("#menu_category_update option:selected").val();
var menu_update_val = $("#menu_update option:selected").val();
if (menu_category_update_val !== "") {
func();
$('#menu_update').val(menuItemSelected).trigger('change');
}
function func() {
$('#menu_category_update').change(function () {
$("#menu_update").empty();
var ddl_menu1 = GetLoadApptUpdate1($(this).val());
$('#menu_update').select2({
placeholder: "--Select Menu--",
data: ddl_menu1,
dropdownParent: $(this).parent()
});
}).change();
function GetLoadApptUpdate1(id) {
var b = [];
$.ajax({
type: "GET",
dataType: "json",
cache: true,
async: false,
url: "/admin/menu/item/entry1/" + id,
success: function (response) {
b = response;
},
error: function (response) {
b = {id: 0, text: "No Data"}
}
});
return b;
};
}

how to get value selected in ajax select2 plugin

html
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
-------------
jquery
$('body').on('click','#Customer_PO',function(e){
id_tosend=$(this).attr("id").toString();
var cust_id=$('#Customer_list').val();
var a=$('#'+id_tosend).select2({
ajax: {
url: 'ajax/report/inspection_report.php?cust_id='+cust_id,
dataType: 'json',
delay: 500,
data: function (params) {
var queryParameters = {
q: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: data
};
},
cache:true
}
});
a.data('select2').dropdown.$dropdown.addClass("test");
$(this).select2('open');
});
i attach plugin of Select2 .When i submitted data in my form ,it shown me empty value . How i get this value to set selected initial value in ajax method.
you can try this
HTML
<label>Customer PO</label>
<select name="Customer_PO" class="form-control" id="Customer_PO" >
<option value="" >Customer PO</option>
</select>
JQUERY
$.ajax({
url: 'url',
type: 'POST',
data: { id: id},
dataType: 'JSON',
success: function (resp) {
if(resp.msg == 'Done'){
$("#Customer_PO option:selected").removeAttr("selected");
$.each(resp.yourListData, function (key, value) {
$("#Customer_PO ").append('<option value="'+value.ID+'">'+value.name+'</option>');
});
$("#Customer_PO ").trigger("change", [true]);
}
},
error: function (e) {
console.log("Line 1204");
console.log(e.responseText);
}
});

InitSelection not work in Select2 4.0.3 js

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']});
});
;
});
}
}

Select2 TypeError: b is undefined

I'm using select2 to show ajax results in a dropdown but when I append data to select2 its showing error
TypeError: b is undefined
JS Code
var baseurl = $("#baseurl").val();
$(".myselect").select2({
placeholder: "Select a inspector",
allowClear: true,
ajax: {
url: baseurl + '/admin/getdata',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.firstname
});
});
return {
results: myResults
};
}
}
});
term.term contains the value of input text in dropdown search box.
HTML
<select class="myselect" style="width: 50% !important">
<option></option>
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
<option value="KY">Kentucky</option>
</select>
JSON RESPONSE
[{"id":9858,"firstname":"Testing3","status":2,"state":"VA","phone":""},{"id":9857,"firstname":"Testing2","status":2,"state":"VA","phone":""},{"id":9856,"firstname":" david polosky ","status":3,"state":"FL","phone":"(000)000-4141"}]
SELECT2 CDN LINKS
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
PHP SERVERSIDE CODE (LARAVEL)
$searchtext = $request->get('term');
$data = Inspector::latest('id')
->select('id', 'firstname', 'status', 'state', 'phone')
->where('firstname', 'LIKE', '%' . $searchtext . '%')
->get()->toArray();
echo json_encode($data);
Any help is appreciated.
In your ajax configuration you use results you should use processResults
Try this
var baseurl = $("#baseurl").val();
$(".myselect").select2({
placeholder: "Select a inspector",
allowClear: true,
ajax: {
url: baseurl + '/admin/getdata',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
processResults: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.firstname
});
});
return {
results: myResults
};
}
}
});
Aamir#, sometimes errors are misleading. If you see from your code, it doesn't have a reference to b at all. I believe that must be an error that is being thrown from a method outside of your code, due to an error in your code.
You might have to set a break point by clicking on the line number on browser console and then check the call stack to find the error in the code.

Autocomplete - change lookup/serviceurl based on dropdown selection

I have a dropdown with multiple options to select. When I select value1 (company), autocomplete should use the service call. When I select value2, lookup should be used.
How can I implement this?
$('#qckSearchKeyword').autocomplete({
serviceUrl: function() {
var option = $('#qck-unspsc').val();
if (option == "country") {
// when country selected through drop down i should use lookup rather then service call
serviceloc = "getCountries";
localStorage.option = "country";
}
if (option == "industry") {
serviceloc = "getSicCode";
localStorage.option = "sicCode";
}
return serviceloc;
},
onSelect: function(suggestion) {
localStorage.tmpSelectedTxt = $.trim($('#qckSearchKeyword').val());
$('#selectFromSuggestions').val("true");
$('#qckSearchKeyword').focus();
},
paramName: "searchTerm",
delimiter: ",",
minChars: 3,
transformResult: function(response) {
// alert(response);
return {
suggestions: $.map($.parseJSON(response), function(item) {
return {
value: item.suggesCode,
data: item.suggesString
};
})
};
}
});
Split up the options for the different autocomplete calls.
Use a data-type on the options you select.
Switch the data-type and extend the proper options
Init autocomplete with proper options
I simply copy/pasted some configuration I've done in the past for this functionality:
...
ajaxOptionsFlight: {
url: '/api/autocomplete/airport/',
type: 'get',
dataType: 'xml'
},
ajaxOptionsHotel: {
url: '/api/locations/hotel/',
type: 'get',
dataType: 'xml'
},
ajaxOptionsCitytrip: {
url: 'http://budapest.onlinetravel.ch/destfinder',
dataType: 'jsonp',
data: {
vendors: 'merger',
client: 'conbe',
filter: 'IATA',
format: 'json',
language: 'en'
}
},
ajaxOptionsCar: {
url: '/api/locations/car/',
dataType: 'json'
},
ajaxOptionsSubstitute: {
url: 'http://gd.geobytes.com/AutoCompleteCity',
dataType: 'jsonp'
},
autocompleteOptions: {
autoFocus: true,
minLength: 1
},
....
After that I make sure I can switch on data-type and hook it on the source parameter of the autocomplete options:
autocompleteOptions = $.extend({}, autocompleteOptions, {
source: type === 'citytrip' ? function (request, response) {
ajaxOptions = $.extend(true, {}, ajaxOptionsCitytrip, {
data: {
name: $.trim(request.term),
language: cookieLanguage
},
success: function (d) {
response($.map(d.Destinations, function (item) {
return {
label: item.name + ', ' + item.country,
value: item.name,
code: item.olt_id
};
}));
}
});
$.ajax(ajaxOptions);
} : type === 'flight' ? function (request, response) {
ajaxOptions = $.extend({}, ajaxOptionsFlight, {
url: ajaxOptionsFlight.url + $.trim(request.term),
success: function (d) {
response($.map($(d).find('airport'), function (item) {
return {
label: $(item).children("displayname").text(),
value: $(item).children("displayname").text(),
code: $(item).children("code").text()
};
}));
}
});
$.ajax(ajaxOptions);
} : type === 'hotel' ? function (request, response) {
// and so on ...
}
});
Not the most elegant way of writing, I admit. But it's basically a simple mapping between data-type and configuration options to provide for autocomplete.
In the end I only call:
input.autocomplete(autocompleteOptions);
And we're done. Hope that makes sense.

Categories

Resources