Unable to preselect value on select2 - javascript

I'm using this library
https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.js">
I know there are a lot of examples out there and I've tried them all most recent:
var $client_id = $("#client_id").select2({
dropdownParent: $('#categoryForm'),
ajax: {
quietMillis: 300,
url: apiPath,
xhrFields: {
withCredentials: true
},
crossDomain: true,
type: "GET",
data: function (params) {
var queryParameters = {
search: params.term
}
return queryParameters;
},
processResults: function (data) {
return {
results: $.map(data.data, function (item) {
return {
text: item.client_name,
id: item.client_id
}
})
};
}
}
});
$client_id.val(6).trigger('change');
As you can see at the bottom I'm trying to select the value using the (valid) ID. I have been successfull using this method:
var option = new Option(data.customer_name, data.customer_id, true, true);
customerSelect.append(option).trigger('change');
But I'd rather just use the ID if it's possible

Related

select2 won't show me results after transforming data into the required format

I use ajax call to fetch data from server and display the results via select2. The problem is that the fetched data is structured in a way that needs to be transformed for select2 to process it correctly.
When I transform data following their documentation, it won't show me the results.
The structure of the response:
{
type1: [{result1}, {result2}, {result3}...],
type2: [{result1}, {result2}, {result3}...],
type3: [{result1}, {result2}, {result3}...]
}
Select2 expects data to be: {"results": [{result1}, {result2}, {result3}...]}
My code:
function formatParent(parent) {
return parent.title || parent.text
}
Ember.$('#parent-select').select2({
ajax: {
url: '/api/parents/' + type,
headers: headers,
dataType: 'json',
data: function (params) {
let query = {
q: params.term,
}
return query;
},
processResults: function (data) {
const res = []
for (let property in data) {
if (data.hasOwnProperty(property)) {
res.push({
"text": property,
"children": data[property]
})
}
}
return res
}
},
width: 'resolve',
theme: 'bootstrap',
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 1,
templateResult: formatParent,
templateSelection: formatParent
})
<select
data-tags="true"
data-placeholder={{placeholder}}
id="parent-select"
style="width: 100%;">
</select>
When I transform the data as presented below the results appear in the dropdown without any problems:
function formatParent(parent) {
return parent.title || parent.text
}
Ember.$('#parent-select').select2({
ajax: {
url: '/api/parents/' + type,
headers: headers,
dataType: 'json',
data: function (params) {
let query = {
q: params.term,
}
return query;
},
processResults: function (data) {
return {"results": data.type1}
}
},
width: 'resolve',
theme: 'bootstrap',
escapeMarkup: function (markup) {
return markup;
},
minimumInputLength: 1,
templateResult: formatParent,
templateSelection: formatParent
})

Select2 AJAX not showing "No data found" when no data in database, instead showing search parameter as option to select

I've been working on a project where I've to load select2 option from ajax call.
The code is working fine, except in search result, it always shows search parameter as option. Even if there is no data in database, it still showing it as option, not showing "No data found".
My code is here
$(".search_user").select2({
minimumInputLength: 11,
tags: [],
ajax: {
url: "/user/get_user",
dataType: 'json',
type: "GET",
quietMillis: 250,
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
var Return = [];
for (var i in data.item) {
console.log(data.item[i])
if (data.item[i].id != data.item[i].text) {
Return.push(data.item[i]);
}
}
return {
results: Return
}
}
}
});
my return json is like this
{"item":[{"id":16,"name":"Razin Abid"}]}
My view is looking like this.
Please help me out.
If you using firemodal on stisla
$('#modal-create-promo').click(()=>{
setTimeout(()=>{
$('#fire-modal-1').removeAttr('tabindex');
});
});
$("#modal-create-promo").fireModal({
...
});
It's work for me
Thats because you enable tags option from select2. You need to remove 'Tags:[]' from your code.
visit : https://select2.org/tagging
so, your code should be like this:
$(".search_user").select2({
minimumInputLength: 11,
ajax: {
url: "/user/get_user",
dataType: 'json',
type: "GET",
quietMillis: 250,
data: function (term) {
return {
term: term
};
},
processResults: function (data) {
var Return = [];
for (var i in data.item) {
console.log(data.item[i])
if (data.item[i].id != data.item[i].text) {
Return.push(data.item[i]);
}
}
return {
results: Return
}
}
}
});

How to use select2 plugin with php and ajax?

I am new to select2 plugin, my problem is,
I want to put a job search option to my web page that is when user queries with keyword php then it will return corresponding data as json. For example if user enters java then it will return most possible words like java, javascript, java.net and user can pick up one or more item from the list displayed.
i did but there is no select option
script
$(".load").select2({
minimumInputLength: 2,
ajax: {
url: "http://localhost/testserver/Test",
dataType: 'json',
type: "post",
data: function (term, page) {
return {
q: term
};
},
processResults: function (data, page) {
console.log(data);
return {
results: $.map(data, function (item) {
return {
text: item.Name,
}
})
};
}
},
});
html
<select class="load" style="width:400px;">
Find below Complete solution
$(document).ready(function() {
$(".load").select2({
minimumInputLength: 2,
ajax: {
url: "http://ip.jsontest.com/",
dataType: 'json',
type: "post",
data: function (term, page) {
return {
q: term
};
},
processResults: function (data, page) {
return {
results: $.map(data, function (item) { console.log(item);
return {
text: item
}
})
};
}
},
});
});
I have pointed url to some other location for dynamic data..Please make changes accordingly

Data not populating the table created using jsgrid

I'm using jsgrid to create an editable table. i used the code from this demo. The only difference is im using mvc instead of web api.
Looking at the network, the controller returns the needed json data and jsgrid also shows the pagination stuff on the bottom of the table. However, the table is not being populated
Here's the html and javascript code
<div id="jsGrid"></div>
#section scripts {
<script src="http://js-grid.com/js/jsgrid.min.js"></script>
<script>
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "get",
data: filter,
dataType: "json"
});
},
insertItem: function (item) {
},
updateItem: function (item) {
},
deleteItem: function (item) {
}
},
fields: [
{ name: "SKU", type: "text", width: 50 },
{ name: "PartNumber", type: "text", width: 100 },
{ name: "ProductLineName", type: "text", width: 50 },
{ name: "ProductLineId", type: "text", width: 50 },
{ name: "Deleted", type: "checkbox", sorting: false },
{ type: "control" }
]
});
</script>
Here's the relevant method in the controller
public async Task<ActionResult> Get()
{
var query = db.Products
.Select(p => new ProductDto()
{
PartNumber = p.PartNumber,
SKU = p.SKU,
ProductLineName = p.ProductLines.ProductLineName,
ProductLineId = p.ProductLineId,
Deleted = p.Deleted
});
var products = await query.ToListAsync();
return Json(products, JsonRequestBehavior.AllowGet);
}
Anyone know what i can do to display/bind the returned data to the table?
Change your loadData call because its not specifying what to do when ajax call is done.
Try to rewrite it like below :
controller: {
loadData: function() {
var d = $.Deferred();
$.ajax({
url: "get",
dataType: "json",
data: filter
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
},
This is the client side javascript that I used which finally put some data in the grid: (just the controller part)
controller: {
loadData: function (filter) {
console.log("1. loadData");
return $.ajax({
type: "GET",
url: "/Timesheet/GetTimesheet/",
dataType: "json",
data: filter
console.log("3. loadData complete");
}
None of the posted explicit promise code functioned at all. Apparently $.ajax returns a promise.
and this was my MVC controller code that I called with ajax (C#):
public async Task<ActionResult> GetTimesheet()
{
int id = Convert.ToInt32(Session["UID"]);
var tl = (
from ts in db.Tasks
orderby ts.Task_Date descending
where ts.Emp_ID == id
select new
{
ID = ts.Task_ID,
Date = ts.Task_Date,
Client = ts.Customer_ID,
Hours = ts.Total_Hours
}
).Take(4);
var jsonData = await tl.ToListAsync();
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
There are no actual examples of required Json for jsGrid. anywhere but this worked for me - note no headers or anything.

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