Jquery autocomplete ui.item undefined using instance option - javascript

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

Related

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.

Jquery UI auto complete (with custom listing) not working

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.

How to make an autocomplete plugins dropdown floats over bootstraps modal box?

I am using jquerys autocomplete plugin to search over a list. In the base of every page autocomplete floats over the page regular. But when i put searchbox in a bootstrap modal dialog box autocomplete dropdown stays at the back and couldn't be displayed. How can i stabilize it on the modal box.
/* the modal caller*/
$('#bizimMesajci').modal();
/* autocomplete plugin codes */
$('#' + nesneID).autocomplete({
source: function (request, response) {
response([{
label: "Aranıyor...",
loading: true
}]);
$.ajax({
url: "evrak_action.php",
data: {
isTipi: 'kurumListesi',
jsonMU: 'evet',
arananKurum: $('#' + nesneID).val()
},
dataType: "json",
type: "POST",
success: function (data) {
//=========================================================<
response($.map(data, function (item) {
return {
label: item.label,
value: item.label,
kID: item.kID
}
}));
//=========================================================<
},
});
},
select: function (event, ui) {
$('#' + nesneIDnum).val(ui.item.kID);
$('#' + nesneID).val(ui.item.label);
//console.log($("#evrakKurumID").val());
return false;
},
focus: function (event, ui) {
return false;
},
minLength: 3
});
http://jsfiddle.net/7zNBH
Just add an optional parameters to autocomplete plugins caller function as described here: http://api.jqueryui.com/autocomplete/#option-appendTo solves my problem.

how enable a button if entered text is valid for autocomplete function?

i have a textbox with autocomplete feature,and a button.I want to enable the button only when a value is selected from the autocomplete list.
how to do this?
Here is my autocomplete function:
<script type="text/javascript">
$(document).ready(function () {
$("#<%=xyz.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebService.asmx/Get") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
},
minLength: 0
}).bind('focus', function () { $(this).autocomplete("search"); });
});
</script>
In your select function add this:
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
$("#buttonid").prop("disabled", true); // true disabled, false enabled
},
EDIT:
$("#buttonid").prop("disabled", false); // this put button enabled
JsFiddle - Example
For a plain button you'll want to set the the button as disabled when the document loads, e.g.
$(document).ready(function () {
$('#btn')[0].disabled = true;
...
and then enable it with the select function, e.g.
select: function (e, i) {
$("#<%=abc.ClientID %>").val(i.item.val);
$('#btn').disabled = false; // <-- enables button
},
Try This: The following will be called when you perform select (use keyboard to select, dont know about mouse select)
$( "#<%=xyz.ClientID %>"" ).on( "autocompleteselect", function( event, ui ) {
$("#buttonid").prop("disabled", false);
});

JSON + PHP + JQuery + Autocomplete problem

Only started today but I'm having massive problems trying to understand JSON/AJAX etc, I've gotten my code this far but am stumped on how to return the data being pulled by the AJAX request to the jQuery Auto complete function.
var autocomplete = new function() {
this.init = function() {
$('#insurance_destination').autocomplete({
source: lookup
});
}
function lookup() {
$.ajax({
url: "scripts/php/autocomplete.php",
data: {
query: this.term
},
dataType: "json",
cache: false,
success: function(data) {
for (key in data) {
return {
label: key,
value: data[key][0]
}
}
}
});
}
}
And example of the JSON string being returned by a PHP script
{
"Uganda": ["UGA", "UK4", "Worldwide excluding USA, Canada and the Carribbean"]
}
Normally, you don't have to do ajax query yourself:
$('#insurance_destination').autocomplete('url_here', {options_here});
That's assuming we're talking about standard jquery autocomplete plugin. Do I understand you correctly?
edit
Check api
http://docs.jquery.com/Plugins/Autocomplete/autocomplete#url_or_dataoptions
There are also some examples.
This is the code I've ended up with, it works in Chrome and Firefox but not in IE 6/7...
var autocomplete = new function (){
this.init = function() {
$('#insurance_destination').autocomplete({
source: function(request, response) {
debugger;
$.ajax({
url: "scripts/php/autocomplete.php",
dataType: "json",
data: {query:this.term},
success: function(data) {
response($.map(data.countries, function(item) {
return {
label: '<strong>'+item.name+'</strong>'+' '+item.description,
value: item.name,
code : item.region
}
}))
}
})
},
minLength: 2,
select: function(event, ui) {
$('#insurance_iso_code_hidden').val(ui.item.code);
},
open: function() {
},
close: function() {
}
});
}
}

Categories