sorry for my bad english. I just wanna ask about select2 ajax, i have problem with this, i don't know how to get other response from my API.
So this is the response from my API.
enter image description here
so i want to get zip_code value when select2 has on changed. but i don't know to get it.
this my code..
$(".myselect").select2(
{
theme: "bootstrap4",
placeholder: "Provinsi, Kota/Kab, Kecamatan, Kelurahan",
minimumInputLength: 3,
ajax: {
url: url, //changing by env
dataType: 'json',
type: "GET",
delay: 150,
data: function (params) {
return {
filter: params.term
};
},
processResults: function (data, params) {
var res = data.data.locations.map(function (item) {
return {
id: item.id,
text: item.name,
zip: item.zip_code
};
});
return {
results: res
};
},
templateResult: function(result) {
return result.text;
},
templateSelection: function(selection) {
return selection.text;
}
},
}).on('change.select2', function(e){
console.log($(this).val(e.text));
villText = $("#village option:last-child").text();
var villVal = $("#village option:last-child").val();
// console.log($("#village option:last-child").val())
// var villVal1 = $("#village option:last-child").val();
villKel = villText;
villKel = villKel.split(',')[2];
$("#village_kel").val(villKel);
var villx = $('#village_land');
var vill_land = $("#village_land option:last-child").text();
vill_land_kel = vill_land;
vill_land_kel = vill_land_kel.split(',')[2];
$("#villageland_kel").val(vill_land_kel);
$('input[name="domisili"]').click(function() {
if ($(this).attr("value") == "1") {
if(villx.empty()) {
villx.append($('<option></option>').attr('value', villVal).text(villText));
villx.prop('selectedIndex', 0);
}
else {
villx.append($('<option></option>').attr('value', "").text(""));
}
}
})
});
picture below is the result when i get the text of value from my API.
enter image description here
Related
I am trying to use "query" object to perform what i want. Everythings works except when i select an option nothing happen (placeholder is not replaced).
I have followed the instructing from this post Loading remote data only once with Select2
init() {
this.$view.select2({
theme: "bootstrap",
language: "fr",
allowClear: this.options.allowClear,
placeholder: this.options.placeholder,
query: (query) => {
if (this.items) {
query.callback({results: this.filterItems(query.term)});
} else {
this.loadData(query);
}
},
templateResult: (state) => {
return this.format(state);
}
});
}
loadData(query) {
$.ajax({
url: this.options.url,
dataType: 'json',
type: 'GET',
success: (data) => {
this.items = [];
for (let row of data) {
this.items.push({
id: row.id,
entity_id: row.entity_id,
text: row.label,
type: row.type,
disabled: !row.enable
});
}
query.callback({results: this.items});
}
});
}
filterItems(term) {
if (typeof term == "undefined" || term === null) {
return this.items;
}
const _term = $.trim(term.toLowerCase());
if (_term === '') {
return this.items;
}
return this.items.filter((item) => {
return item.text.toLowerCase().includes(term);
});
}
Thanx for help,
I think i have found a solution :
var s2data = $view.select2({
ajax: {
url: 'https://api.github.com/search/repositories',
data: {
q: 'select2'
},
dataType: 'json',
processResults: function(data) {
var items = [];
for (var row of data.items) {
items.push({
id: row.id,
text: row.name
});
}
this.options.set('cacheDataSource', {items: items});
return {
results: items
};
}
},
cacheDataSource: [],
allowClear: true,
placeholder: 'Select Values ...',
width: '100%',
}).data('select2');
s2data.dataAdapter.query = function(params, callback) {
var cacheDataSource = this.options.get('cacheDataSource');
if (cacheDataSource && cacheDataSource.items) {
var term = params.term;
if (typeof term == "undefined" || term == null) {
callback({results: cacheDataSource.items});
return
}
term = $.trim(term.toLowerCase());
if (term == "") {
callback({results: cacheDataSource.items});
return
}
callback({ results: cacheDataSource.items.filter(function(item) {
return item.text.toLowerCase().includes(term);
})
});
} else {
// call the original logic
var ajaxAdapterFunc = jQuery.fn.select2.amd.require('select2/data/ajax');
var ajaxAdapter = new ajaxAdapterFunc(this.$element, this.options);
ajaxAdapter.query(params, callback);
}
}
jsfiddle : https://jsfiddle.net/3kpu4htm/35/
I am using select2 plugin(ivaynberg.github.io/select2).
I am trying to display a dropdown(select).
Data getting via ajax, for this I create 2 servlets.
Dropdown menu url: '/testPr1/servlet1'
Return:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"},{"id":3,"text":"Genre3"},{"id":4,"text":"Genre4"}]
Init data url: '/testPr1/servlet2'
Return:
[{"id":1,"text":"Genre1"},{"id":2,"text":"Genre2"}]
I create hidden element for select2 (and set init value)
Select film genre from list:
<input type="hidden" id="film_genre_cbox" style="width:600px" value="1,2" />
Then I get started with creating dropdown
var select_config2 = {
minimumInputLength: 0,
allowClear: true,
placeholder: "Select film genre",
tags: true,
ajax: {
url: '/testPr1/servlet1',
dataType: 'json',
type: "GET",
quietMillis: 0,
data: function (term) {
return {
term: term
};
},
initSelection: function (element, callback) {
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
}
};
$("#film_genre_cbox").select2(select_config2);
It works well, select exclude Genre1 and Genre2 as init value
But I want to see these two genres as selected elements in input, like this:
And then I tried to init select2 via ajax
var select_config1 = {
minimumInputLength: 0,
allowClear: true,
placeholder: "Select film genre",
tags: true,
ajax: {
url: '/testPr1/servlet1',
dataType: 'json',
type: "GET",
quietMillis: 0,
data: function (term) {
return {
term: term
};
}
},
initSelection: function (element, callback) {
var id = $(element).val();
// alert(id.toString());
if (id !== "") {
$.ajax({
url:'/testPr1/servlet2',
dataType: "json",
type: "GET",
quietMillis: 0,
}).done(function(data) {
alert(data.toString());
return callback(data);
});
} else {
callback([]);
}
},
results: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.text,
id: item.id
}
})
};
}
};
$("#film_genre_cbox").select2(select_config1);
As result I get init selection as want
But when I start to dropdown I get no menu (Genre3,Genre4)
and error “Uncaught TypeError: options.results is not a function”.
Libs that I use
jquery-2.1.4.js
/select2_v3.5/select2.js
select2_v3.5/select2.css
Where is the mistake?
Here is the web method, which I use before for another thing, and it works:
[WebMethod]
public static string GetTests()
{
return GetData().GetXml();
}
public static DataSet GetData()
{
DataSet ds = new DataSet();
BusinessLayer.StudentsController oStudent = new BusinessLayer.StudentsController();
oStudent.Action = "page";
oStudent.PageIndex = 0;
oStudent.PageSize = int.Parse(System.Configuration.ConfigurationManager.AppSettings["PageSize"].ToString());
DataTable dt1 = oStudent.Select();
DataTable dt2 = dt1.Copy();
dt2.TableName = "Students";
ds.Tables.Add(dt2);
DataTable dt = new DataTable("PageCount");
dt.Columns.Add("PageCount");
dt.Rows.Add();
dt.Rows[0][0] = oStudent.PageCount;
ds.Tables.Add(dt);
return ds;
}
JavaScript:
$('#selectDynamic1').select2({
placeholder: "Search for a movie",
minimumInputLength: 1,
multiple: true,
ajax: {
url: "Default.aspx/GetTests",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
formatResult: formatResult,
formatSelection: formatSelection,
/*initSelection: function(element, callback) {
var data = [];
$(element.val().split(",")).each(function(i) {
var item = this.split(':');
data.push({
id: item[0],
title: item[1]
});
});
//$(element).val('');
callback(data);
}*/
});
function formatResult(node) {
alert('');
return '<div>' + node.id + '</div>';
};
function formatSelection(node) {
alert('');
return node.id;
};
Please help, GetTests is not even firing, I want to bring the student through SQL then fill the select2.
First, you shoul ry to change the HTTP verb to GET, as you are not posting data to the server, you want to get data from it:
ajax: {
...
type: 'GET',
...
}
Secondly, you are expecting JSON from the server, but in the GetData method, you are creating an XML document - at least the code conveys this. This may be one cause, why your code does not work.
I am passing complex JSON data to jQuery autocomplete plugin. And it is working fine so it shows the list of Products.
Now I want to get somehow Price that is already included into JSON data and when I select product from autocomlete list I would like to populate input tag with Price.
I really cannot get if it is possible to do. What I know that data is already in JSON but how to get it?
Any clue?
Here is JS for jQuery autocomplete plugin
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
}
});
});
}
To make clear item.LastPrice has Price data.
And HTML
#Html.AutocompleteFor(x => x.ProductUID, Url.Action("AutocompleteProducts", "Requisition"), true, "Start typing Product name...", Model.Product.Name)
In your ui.item object you should be able to find the the Price property in there and then set the value in the select function.
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
price: item.LastPrice // you might need to return the LastPrice here if it's not available in the ui object in the select function
};
}));
},
..
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name'),
unitPriceEl = $('#price');
$('#' + hiddenFieldName).val(ui.item.UID);
unitPriceEl.val(ui.item.LastPrice); //set the price here
}
Thanks to dcodesmith!!! I am gonna mark his solution like an answer but just in case I will share my final code that is working fine now.
function CreateAutocomplete() {
var inputsToProcess = $('[data-autocomplete]').each(function (index, element) {
var requestUrl = $(element).attr('data-action');
$(element).autocomplete({
minLength: 1,
source: function (request, response) {
$.ajax({
url: requestUrl,
dataType: "json",
data: { query: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Name,
value: item.Name,
realValue: item.UID,
lastPrice: item.LastPrice
};
}));
},
});
},
select: function (event, ui) {
var hiddenFieldName = $(this).attr('data-value-name');
$('#' + hiddenFieldName).val(ui.item.UID);
var unitPriceEl = $('#UnitPrice');
unitPriceEl.val(ui.item.lastPrice);
console.log(ui.item.lastPrice);
}
});
});
}
I'm sorry similar post is already there in the community, But i'm finding it strange. Its working fine but it affected my other views and not allowing other view pages to populate any dialogue boxes..
I tried to fix it by wrapping it in function() like this
$('#_auto').autocomplete(function(){
But, with this i'm not getting jason values in the _auto textfield and getting unexpected token error with following line.
can anyone help me to solve this please.
source: function(request,response){
this is my code:
$(function () {
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
var sval = $('#_auto').val();
//alert(sval);
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': sval,
},
dataType: 'json',
success: function (data) {
console.log(data);
var dta = [];
orgdetails = [];
//response(data.d);
for (var i in data) {
dta.push(data[i].name);
orgdetails[data[i].name] = data[i].id;
}
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});
});
Many Thanks
I think the for loop should be
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
Fiddle.
Another observation, You can get the current searched term using request.term rather than $('#_auto').val()
Complete code:
$('#_auto').autocomplete({
selectFist: true,
minLength: 2,
source: function (request, response) {
$.ajax({
url: BASE_URL + '/controller/search/',
type: 'POST',
data: {
'term': request.term,
},
dataType: 'json',
success: function (data) {
console.log(data);
orgdetails = {};
var dta = $.map(data, function(v, i){
orgdetails[v.name] = v.id;
return {
label: v.name,
id: v.name
};
});
response(dta); //response(dta);
},
error: function (result) {}
}); //ajax
}
}).focus(function () {
$(this).trigger('keydown.autocomplete');
});