programatically set custom data to select2 - jquery-select2-4

How can I set custom data to a select2 v.4 per javascript? I understand that you can set the id and text value by inserting an option tag but that does not cover all the other data I want to have there in addition, e.g. [{"id":"17","text":"22.09.2015 15:45:05","branchList":["20","1","3","4","5"]}]
I use this code to set up the control, which works perfect:
$('#image_id').select2({
placeholder: "Search image ...",
minimumInputLength: 0,
allowClear: true,
dropdownAutoWidth: true,
theme: "bootstrap",
ajax: {
url: "ajax/select2_image_search.php",
delay: 250,
dataType: 'json',
data: function (params) {
return {
keywords: params.term
};
},
processResults: function (data, page) {
return {
results: data
};
}
},
});
when I then use this code, I can extract not only id and text but also custom data like branchList:
var bList = $('#image_id').select2("data")[0]["branchList"];
this works well too, but how can I set the additional info programatically per script with e.g. this data [{"id":"18","text":"23.09.2015 15:45:05","branchList":["22","5","7","32","1"]}] so that I can retrieve the additional info lateron per javascript?
Thanks a lot for your help :)

Simplest way is put your custom data to id with JSON.stringify(). Maybe it is not good way but it works for me.
So your code transforms to:
[ {
"id" : JSON.stringify({
"id" : "18",
"branchList" : [ "22", "5", "7", "32", "1" ]
}),
"text" : "23.09.2015 15:45:05"
} ]
And you can later extract your data back by JSON.parse(selector.selectedOptions[0].value).

Related

What data structure is select2 expecting from the server and how should it be handled?

What data structure is select2 (v4.0.3) expecting from the server and how should it be handled?
The question is asked on the official FAQ here, but there is no answer.
I have tried several variations of data structure, but based on this tutorial and this jsFiddle, have assumed what should be returned from the server is a list/array of objects/dicts, eg:
matches = [{"id":"1", "tag":"Python"},{"id":"2", "tag":"Javascript"},{"id":"3", "tag":"MongoDB"}]
I have tried this format with the following Javascript:
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data.matches
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});
Firebug results for search on Py:
The search area just displays this:
I am expecting all matches to be showing in the dropdown below the search area.
Solution that worked for me:
Rename json key (it has to be text), so server response is:
[{"text": "Python", "id": 1}]
(after coming across this document).
I also just returned the list itself from the server, rather than making the list a dict value.
Javascript
$("#my_select").select2({
ajax: {
url: "/tag_search",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 2,
tags: true,
tokenSeparators: [",", " "],
maximumSelectionLength: 5
});

Geo sorting and distance calculation in ElasticSearch not working

UPDATE I've also updated the mapping to include pin as the examples seem to suggest. Also, here's an temporary instance with some data to work with: https://21991e47cdc7caa8000.qbox.io/profiles/lead/_search
I've followed the instructions by ElasticSearch. Using this request:
$.ajax({
url: 'https://21991e47cdc7caa8000.qbox.io/profiles/lead/_search',
method: 'GET',
data: {
sort: [{
_geo_distance: {
"pin.location": [49.8998, -97.1375],
order: "asc",
unit: "km"
}
}]
},
success: function(response) {
console.log(response);
}
});
Does not return with calcuated distance or sorted by distance. I've also tried using "location".
Here's my mapping: https://21991e47cdc7caa8000.qbox.io/profiles/lead/_mapping
Any ideas?
I've managed to get it working, Please see the difference,
I converted data as json before quering, and added some configuration( changed dataType to json, and request type to POST, as we know GET request generally don't have body, only POST request does.
var request = {
sort: [{
_geo_distance: {
"pin.location": [
49.8998, -97.1375],
order: "asc",
unit: "km"
}
}]
};
$.ajax({
url: 'https://21991e47cdc7caa8000.qbox.io/profiles/lead/_search',
type: 'POST',
crossDomain: true,
dataType: 'json',
data: JSON.stringify(request),
success: function (response) {
console.log(JSON.stringify(response));
}
});
Hope this helps.
I've tested, and it should work for you too.
The example given uses pin.location, not location or lead.location.
Additionally, pin.location is an array of length 2, not an object with two fields as you are using it. This seems pretty counter-intuitive to me, as the location field in most other api calls is an object like you are using.
Try this:
$.ajax({
url: "https://myhostedes.com/profiles/lead/_search",
method: "GET",
data: {
"sort": [{
"_geo_distance": {
"pin.location": [49.8998, -97.1375],
"order": "asc",
"unit": "km"
}
}]
},
success: function(response) {
console.log(response);
}
});
Note: I don't have access to an elastisearch instance at the moment, so I haven't been able to run this yet.

select2 remote displaying label instead of id when selecting a value from results

I have the following code in an attempt when selecting a suggestion to display the selected value instead of the id. BUT I still need to pass the id as a value. This works fine when using select2 without remote on a regular select box, but it doesn't seem to work like this on a remote data source using an input.
Here is my results:
Search suggestions (working):
Selection Result (Not working as expected..I expect the search suggestion to be selected):
Here is the code:
$("#specific_input_data").select2(
{
minimumInputLength: 2,
placeholder: <?php echo json_encode(lang('common_search')); ?>,
id: function(suggestion){ return suggestion.value; },
ajax: {
url: <?php echo json_encode($search_suggestion_url); ?>,
dataType: 'json',
data: function(term, page)
{
return {
'term': term
};
},
results: function(data, page) {
return {results: data};
}
},
formatSelection: function(suggestion) {
return suggestion.value;
},
formatResult: function(suggestion) {
return suggestion.label;
}
});
I figured i out. formatSelection needs to be selection.label

Need help with jqGrid and navGrid

With the main part of the jqGrid there is the postData parameter that can be set to add stuff to the POST variable. Is there a way I could do the same thing with the navGrid?
Here is what I have:
main jqGrid script
$("#"+id).jqGrid({
url:baseURL+'modules/'+module+'/config.php',
postData: {event: 'load-content',content : id,module: module},
datatype: 'json',
mtype: 'POST',
colNames:colNames,
colModel:colModel,
pager: '#pager',
rowNum:limit,
rowList:[10,20,30],
autowidth: true,
sortname: sortby,
sortorder: 'desc',
gridview: true,
viewrecords: true,
caption: title,
editurl: baseURL+'modules/'+module+'/config.php'
});
navGrid script
jQuery("#"+id).jqGrid('navGrid','#pager',
{del:true,add:true,edit:true}, //options
{height:280,reloadAfterSubmit:false}, // edit options
{height:280,reloadAfterSubmit:false}, // add options
{reloadAfterSubmit:false}, // del options
{});
What I want is to add {module: module, event: 'del-test'} to the POST of the delete button.
You can use additional editData (for add or edit operations) or delData parameter (for delete operation) and change the del options used as a parameter of 'navGrid' from
{reloadAfterSubmit:false}
to
{reloadAfterSubmit:false, editData:{module: module, event: 'del-test'}}
(the variable module should be defined before).
By the way, like with postData parameter (see this old answer) you can use function for any property of editData parameter:
{
reloadAfterSubmit:false,
delData: {
module: function() {
return "bla bla";
},
event: 'del-test'
}
}
I know it's a long time since you posted this question, I wanted to improve it anyways the wiki pages shows you the basic use of the navgrid and this is the answer that worked for me.
Best regards,
Modify your code this way
$("#" + id).jqGrid('navGrid', '#pager',
{ add: true, edit: true, del: true },
{ height:280, reloadAfterSubmit:false },
{ height:280, reloadAfterSubmit:false },
{
// settings for Delete
mtype: "post",
reloadAfterSubmit: false,
onclickSubmit: function (rp_ge, postdata) {
rp_ge.url = '<%: Url.Content("~/URL/TO/DELETE/METHOD/HERE") %>' + postdata;
},
serializeDelData: function (postdata) {
postdata.module = module;
postdata.event = 'del-test';
return postdata;
}
},
{},
{}
);

json object submitted as application/x-www-form-urlencoded to mvc controller

I have an array:
var list = JSON.parse('[{"id" = "8", "description" = "test"},{"id" = "10", "description" = "test_2"}]');
I'm using this together other data to post using jQuery's ajax method:
var data = { start: 123403987, list };
Why is the values submitted as:
start=123403987&list[0][id]=8&list[0][description] = "test"...
Where I am expecting:
start=123403987&list[0].id=8&list[0].description = "test"...
Because that's the default content type. You could specify a different type. Also make sure you have a valid JSON object (which is not your case, use : instead of = for properties) or the server side script might choke:
$.ajax({
type: 'POST',
url: '/foo',
data: '[{ id: "8", description: "test" }, { id: "10", description: "test_2"}]',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(result) {
alert('ok');
}
});
You are using poorly formatted JSON, it should be of the form:
var list = JSON.parse('[{"id": "8", "description": "test"},{"id": "10", "description": "test_2"}]');

Resources