Jquery UI auto complete (with custom listing) not working - javascript

I am trying to use jquery UI autocomplete, but somehow the same won't show up despite having no javascript error.
here is my json data:
{"d":"[{\"label\":\"XYZ\",\"desc\":\"desc 1\",\"value\":\"XYZ\",\"ID\":595,\"icon\":\"UM-892983\"},{\"label\":\"ABC .\",\"desc\":\"desc 2\",\"value\":\"ABC .\",\"ID\":1681,\"icon\":\"UM-432944\"}]"}
Here is my JS Function for processing the autocomplete:
$().ready(function(){
$("#txtName").bind("keyup", function (e) {
// Ajax call returns the above json data
// On Ajax Success I call
onSucName(returnData.d);
});
});
function onSucName(result) {
var varArrAdms = $.parseJSON(result);
$("#txtName").autocomplete({
source : varArrAdms,
select : function (event, ui) {
setNameValue(ui.item.icon)
$("#txtNo").val(ui.item.icon)
$("#btnSearch").click();
},
open : function () {
$(this).addClass('loadingTxtBox');
},
close : function () {
$(this).removeClass('loadingTxtBox');
}
}).data("ui-autocomplete")._renderItem = function (ul, item) {
return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.value + " <b> desc:" + item.desc + "</b> <i> No:" + item.icon + "</i></a>").appendTo(ul);
};
}
Where am I wrong?

Try this example
$('#txtName').autocomplete({
source: function (request, response) {
$.ajax({
url: 'url',
data: {}, //pass data here
dataType: 'json',
type: 'post',
success: function (data) {
response($.map(data, function (item) {
return {
label: item.icon
}
}));
}
})
},
select: function (event, ui) {
var itemval = ui.item.label;
// here you can access selected result `itemval`
return false;
},
minLength: 1
});

Why are you binding the autocomplete on keyup.... Rather you should bind it once.
Also, before rebinding it you shoud destroy the existing instance.

Related

Jquery autocomplete ui.item undefined using instance option

I am using jquery ui 1.12.1 and jquery 3.1.1. I'm trying to get my autocomplete working. So far I have results displaying and populating correctly. However I'm running into an issue with ui.item being undefined in the select function. Which is causing all sorts of issues down the line. I've seen several other questions on the topic but none specifically using the instance option. Any help to point me in the direction would be appreciated.
http://api.jqueryui.com/autocomplete/#method-instance
Jquery Autocomplete Select TypeError: ui.item undefined
$("#municipality").blur(function () {
var keyEvent = $.Event("keydown");
keyEvent.keyCode = $.ui.keyCode.ENTER;
$(this).trigger(keyEvent);
}).autocomplete({
minLength: 3,
autoFocus: true,
position: { collision: "flipfit" },
source: function (request, response) {
var muniUrl = serviceUrl + "sns/getinfobyterm?term=" + encodeURIComponent(request.term);
$.ajax({
url: muniUrl,
contentType: 'application/json',
xhrFields: {
withCredentials: true
},
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + webServiceToken);
},
type: 'get',
error: function (ret) {
BccViewModel.errorForUser("Unable to get municipalities. Please try again later.");
$("#FinancialErrorPopup").modal();
console.log(ret);
},
success: function (ret) {
response(ret);
},
complete: function (ret) {
$("#municipality").removeClass("ui-autocomplete-loading");
}
});
},
select: function (event, ui) {
ClearModelAfterMunicipalityChange();
if (ui.item !== null) {
ProcessMunicipalityData(ui.item);
};
},
close: function () {
// change what's displayed in the input field to just the town name instead of full label from the autocomplete
$("#municipality").val(SnsViewModel.municipality());
}
}).autocomplete("instance")._renderItem = function (ul, item) {
return $("<li>")
.append("<div>" + item.MunicipalityInfo.MunicipalityLabel + "</div>")
.appendTo(ul);
};

Jquery autocomplete - how modify returned data

I have code like this:
$(document).ready(function () {
if ($('#au').length <= 0) {
return;
}
var $project = $('#au');
$project.autocomplete({
minLength: 4,
source: function (request, response) {
$.ajax({
dataType: "json",
type: 'post',
cache: false,
data: {term: request.term},
url: '/Movies/ajax/',
success: function (data) {
if (isNaN($('#au').val())) {
response($.map(data, function (item) {
return {
label: item.Movies__name + " " + "(" + item.Movies__id + ")",
value: item.Movies__name
}
}));
} else {
response($.map(data, function (item) {
return {
label: item.Movies__id + " " + "(" + item.Movies__name + ")",
value: item.Movies__id
}
}));
}
}
});
},
select: function(event, ui) {
$("#au").val(ui.item.value);
$("#au").submit();
},
create: function (event, ui) {
},
open: function (event, ui) {
}
});
});
This code works fine. Basicly when You type in form "Alie", you will get
Alien(22)
Aliens2(32)
Aliens3(43)
Or when you type Id istead of movie name, you will get:
(22)Alien
(22)Other and so on....
So this code returns list of data - movie and id.
And now i want, to have first result without id, so when You type movie name like "Alie" you will get:
Alien
Alien(22)
Aliens(32)
First match without id.
Thanks for any replies.
response($.map(data, function (item, i) {
return {
label: item.Movies__name + (i != 0 ? " (" + item.Movies__id + ")" : ""),
value: item.Movies__name
}
}));
Use i for index in map function. If 0, you don't show id.

Not able to get data in the dataFilter function

I am trying to filter the json array received from the server. I'm able to receive the data properly in the success function however I get a "data is undefined error" within the filterdata block. [Uncaught TypeError: Cannot read property 'list' of undefined]
$(function () {
function log(message) {
$("<div>").text(message).prependTo("#log");
$("#log").scrollTop(0);
}
$("#city").autocomplete({
source: function (request, response) {
$.ajax({
url: "http://api.openweathermap.org/data/2.5/find?mode=json&type=like",
dataType: "jsonp",
data: {
q: request.term
},
dataFilter: function (data, type) {
console.log(data);
alert(data.list.length);
alert(data.list[0].name + ', ' + data.list[0].sys.country);
jsonObj = [];
for (i = 0; i < data.list.length; i++) {
item = {}
item["city"] = data.list[0].name;
item["country"] = data.list[0].sys.country;
jsonObj.push(item);
}
return jsonObj;
},
success: function (data) {
//alert(data.list.length);
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
log(ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
As dataFilter is a function to be used to handle the raw response data of XMLHttpRequest. Since you are using JSONP request, which is not an XHR request so there is no XHR object and no raw data, which makes the behavior of dataFilter in your case perfectly valid. You should check the response in success callback instead.

How to get the $(this) to work in JQueryUI autocomplete

Here is a fiddle example
I have trouble getting the $(this) to work in the source function with jQueryUI autocomplete.
The console shows that the search input isn't able to get its data attribute 'name' before sending out an Ajax request. Is there any way to pass the variable "name" to data?
$('.input').autocomplete({
source: function (request, response) {
var name = $(this).data('name');
console.log(name);
$.ajax({
url: url,
dataType: "json",
data: {
'q': request.term,
'field': name
},
success: function (data) {
response($.map(data.query.results.json.json, function (item) {
return {
label: item.name,
}
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(this).val(ui.item.label);
$(this).val(ui.item.label);
},
open: function () {
$(this).autocomplete("widget").width(400)
}
});
You should use this.element to access corresponding input element. this points to the autocomplete instance itself:
var name = $(this.element).data('name');

How to populate extra fields with jQuery autocomplete

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

Categories