Cannot get selected item in jquery autocomplete - javascript

Using Jquery autocomplete UI widget, I have the following code that gets a list of suburbs/postcodes via external php:
<script>
$(function() {
$("#suburb").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'resources/php/helpers.php', //your server side script
dataType: 'json',
data: {
suburb: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
},
select: function (event, ui) {
alert("SELECT");
$('#postCode').val("POSTCODE");
return true;
}
});
}
});
});
</script>
The autocomplete itself works well, I get the list of matches , however the 'select' part does not work, ie, I need to set another input text value to the value selected, but even in the above code, the Alert dialog does not get called - the various syntax I've seen has kind of confused me, so I'm not sure what I've done wrong here.

The selectfunction should be outside of the object that is sent to the ajax method.
Try this:
$(function() {
$("#suburb").autocomplete({
minLength:3, //minimum length of characters for type ahead to begin
source: function (request, response) {
$.ajax({
type: 'POST',
url: 'resources/php/helpers.php', //your server side script
dataType: 'json',
data: {
suburb: request.term
},
success: function (data) {
//if multiple results are returned
if(data.localities.locality instanceof Array)
response ($.map(data.localities.locality, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
//if a single result is returned
else
response ($.map(data.localities, function (item) {
return {
label: item.location + ', ' + item.postcode,
value: item.location + ', ' + item.postcode
}
}));
}
});
},
select: function (event, ui) {
alert("SELECT");
$('#postCode').val("POSTCODE");
return true;
}
});
});

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

jquery ui autocomplete custom data (item undefined )

My Script
$("#NameSearch").autocomplete({
minLength: 0,
source: function (request, response) {
$.ajax({
url: "/home/universalsearch/" + document.getElementById("filterUniversalSearchList").value + "/" + $("#NameSearch").val(),
type: "POST",
dataType: "json",
data: {
searchFilter: document.getElementById("filterUniversalSearchList").value,
term: request.term,
},
success: function (data) {
response($.map(data, function (item) {
return { label: item.EmployeeName, id: item.EmployeeID}
}))
}
});
},
focus: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
},
select: function (event, ui) {
$("#NameSearch").val(ui.item.label);
return false;
}
})
.autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<div>" + item.label + "<br>" + item.id + "</div>")
.appendTo(ul);
};
});
Controller:
public JsonResult UniversalSearch(string searchFilter, string searchText)
{
var Employees = _home.GetEmployeeDetails(searchFilter, searchText);
return Json(new { data = Employees }, JsonRequestBehavior.AllowGet);
}
Problem I'm facing is in autocomplete dropdown I'm getting as undefined.
From controller it return as object array
I think I made mistake in binding data improperly.
dropdown result shows as undefined.
Is this problem due to jqueru-ui versions ?

C# Webservice json data jquery ui with custom formatting

I'm using asp.net webservice to use it in jQuery UI autocomplete plugin and here is the data I'm getting.
{"d":[
{
"__type":"WebS.Model.SearchModel",
"MainCommodityId":1,
"MainCommodityName":"Pulses",
"SubcommodityId":3,
"SubCommodityName":"Urid Dal",
"BrandId":3,
"BrandName":"President"
},
{
"__type":"WebS.Model.SearchModel",
"MainCommodityId":1,
"MainCommodityName":"Pulses",
"SubcommodityId":1,
"SubCommodityName":"Red Gram",
"BrandId":4,
"BrandName":"President"
}
]
}
This is the script I'm using:
$(document).ready(function () {
$(".input-search").autocomplete({
source: function (request, response) {
$.ajax({
url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
data: "{ 'data': '" + request.term + "'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
value: item.BrandName,
label: item.SubCommodityName
}
}))
},
error: function (response) {
alert('error');
},
failure: function (response) {
alert('faii');
}
});
},
select: function (e, i) {
console.log(i.MainCommodityId);
console.log(i.SubcommodityId);
console.log(i.BrandId);
},
minLength: 1
}).autocomplete("instance")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + "" + item.BrandName + " in " + item.MainCommodityName + " - " + item.SubCommodityName + "</a>")
.appendTo(ul);
};
});
The issues are:
When I tried to enter keyword say: pre the aforesaid output is coming in json. However, the list is returning only one "President" item where it should display 2 items.
The list is displaying "undefined in undefined - undefined" instead of values after adding .autocomplete("instance")._renderItem function.
console.logs are also undefined after selecting an item.
How can these issues fixed?
The default behavior of the select event is to update the input with ui.item.value. This code runs after your event handler.
Simply prevent the default action on select and focus using event.preventDefault() or by return false and use _renderItem for custom dropdown.
focus: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault(); // or return false;
}
select: function(event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
//do something
}
References:
jQuery UI Autocomplete Examples
Example 2
Finally, I was able to achieve what I wanted. Answering my question as it may helpful to someone.
javascript:
$(document).ready(function () {
$(".input-search").autocomplete({
source: function (request, response) {
$.ajax({
url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
data: "{ 'data': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
// don't forget to $.map to (data.d where d is the top node
return {
// assign values from json response for further use
brandid: item.BrandId,
brand: item.BrandName,
maincommodityid: item.MainCommodityId,
maincommodity: item.MainCommodityName,
subcommodityid: item.SubcommodityId,
subcommodity: item.SubCommodityName
}
}));
},
error: function (response) {
alert('Server Error. Please try again.');
},
failure: function (response) {
alert('Failed to get result');
}
});
},
focus: function (event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
},
select: function (event, ui) {
// prevent autocomplete from updating the textbox
event.preventDefault();
// do further action here such as assigning id to hidden field etc.
$(".input-search").val(ui.item.brand);
// navigate to the selected item's url ex: /catalogue/1/1/pulses/red-gram/4/president
var str = "/catalogue/" + ui.item.maincommodityid + "/" +
ui.item.subcommodityid + "/" + $.trim(ui.item.maincommodity.replace(/\s+/g, '-').toLowerCase()) + "/" +
$.trim(ui.item.subcommodity.replace(/\s+/g, '-').toLowerCase()) + "/" + ui.item.brandid + "/" +
$.trim(ui.item.brand.replace(/\s+/g, '-').toLowerCase());
window.location = str;
},
minLength: 3
}).autocomplete("instance")._renderItem = function (ul, item) {
// get values and create custom display
var $a = $("<a></a>");
$("<strong></strong>").text(item.brand).appendTo($a);
$("<span></span>").text(" in ").appendTo($a);
$("<span></span>").text(item.subcommodity).appendTo($a);
return $("<li></li>").append($a).appendTo(ul);
};
});
CSS:
ul.ui-front {
z-index: 1200; // change z-index according to your UI.
}
Usually I do this way and Its work.
$(document).ready(function () {
var jsondata=array();
$.post("/WebServices/GetAllBrandNames.asmx/getAllBrands",{data: request.term},function(data){
var data=JSON.parse(data);
$.each(data.d, function( index, value ) {
jsondata[index].value=value;
});
$(".input-search").autocomplete({
source:jsondata,
//other property and events
})
});
I mean apply source JSON after completing request because sometimes if AJAX takes some time to load execution pointer still execute rest of code without waiting for response.
I did not test this code but I always do this way and never get your kind of error. Good Luck

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.

JQuery Autocomplete select undefined error

I've been ripping my hair out for a few hours now and can't seem to find out why i've got an error.
When i call the following code :
$(document).ready(function () {
$("#searchBox").autocomplete({
select: function (event, ui) {
$("#searchBox").attr("readonly", true);
//this is where if i call alert(ui.long) I get undefiend
$("#CoorLong").val(ui.long);
$("CoorLat").val(ui.lat);
print_r(ui);
},
source: function (request, response) {
$.ajax({
url: "http://dev.virtualearth.net/REST/v1/Locations",
dataType: "jsonp",
data: {
key: "bingKey",
q: request.term
},
jsonp: "jsonp",
success: function (data) {
var result = data.resourceSets[0];
if (result) {
if (result.estimatedTotal > 0) {
response($.map(result.resources, function (item) {
return {
data: item,
label: item.name + '[' + item.point.coordinates[0] + ' ' + item.point.coordinates[1] + ']' + ' (' + item.address.countryRegion + ')',
value: item.name,
long: item.point.coordinates[0],
lat: item.point.coordinates[1]
}
}));
}
}
}
});
},
minLength: 1
});
});
As I said in the selec: function(event, ui) when i call ui.item or ui.value or ui.long I always get undefined
I implemented a print_r() to check the content and I do get this :
[item] =>object[data] =>object[__type] =>Location:http://schemas.microsoft.com/search/local/ws/rest/v1[bbox] =>object[0] =>48.83231728242932[1] =>2.2598159619433122[2] =>48.840042717570675[3] =>2.275464038056688[name] =>Quai d'Issy-les-Moulineaux, 75015 Paris[point] =>object[type] =>Point[coordinates] =>object[0] =>48.83618[1] =>2.26764[address] =>object[addressLine] =>Quai d'Issy-les-Moulineaux[adminDistrict] =>IdF[adminDistrict2] =>Paris[countryRegion] =>France[formattedAddress] =>Quai d'Issy-les-Moulineaux, 75015 Paris[locality] =>Paris[postalCode] =>75015[confidence] =>Medium[entityType] =>RoadBlock[label] =>Quai d'Issy-les-Moulineaux, 75015 Paris[48.83618 2.26764] (France)[value] =>Quai d'Issy-les-Moulineaux, 75015 Paris[long] =>48.83618[lat] =>2.26764
So i don't understand why it's undefined.
Thank you :)
From the documentation:
ui.item refers to the selected item.
So I think you want ui.item.long instead of ui.long.

Categories

Resources