How to customize the found items in autocomplete() UI? - javascript

I am trying to change how the found items are displayed in the autocomplete UI This autoComplete wigide is used inside of a dialog box.
I tried to use the '_renderMenu' property like the code below but the found items are displayed blank "no data"
Here is my code
$("#icwsTransferTo").autocomplete({
minLength: 2,
source: function(request, response) {
$.ajax({
type: 'GET',
url: 'index.php',
data: {method: 'userSearch', term: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
if(!data){
return;
}
var allFound = $.map(data, function(m) {
return {
'name': m.configurationId.displayName,
'ext': m.extension,
'id': m.configurationId.id
};
});
response(allFound);
}
});
},
select: function( event, item) {
alert(item.value + ' was selected!!!');
},
'_renderItem': function (ul, item) {
return $( "<li>" ).attr( "data-value", item.id)
.append( '<span>' + item.name+ '</span><span style="float: right"> (' + item.ext + ')</span>' )
.appendTo( ul );
}
});

I figured it out...
Here is the new code for anyone that is searching. I found this article as a great resource.
$.widget("custom.autoCompleteUserList", $.ui.autocomplete, {
_renderItem: function (ul, item ) {
if(item.ext != 'undefined' && typeof item.ext !== 'undefined'){
var label = '<div class="ui-autocpmplete-item-wrapper"><span class="ui-autocpmplete-item-name-span">' + item.name + '</span><span class="ui-autocpmplete-item-ext-span"> (ext. ' + item.ext + ')</span></div>';
} else {
var label = '<div class="ui-autocpmplete-item-wrapper">' + item.name + '</div>';
}
return $( "<li>" )
.attr( "data-value", item.id )
.append( label)
.appendTo( ul );
}
});
$("#icwsTransferTo")
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autoCompleteUserList( "instance" ).menu.active ) {
event.preventDefault();
}
}).autoCompleteUserList({
minLength: 2,
source: function(request, response) {
$.ajax({
type: 'GET',
url: 'index.php',
data: {method: 'userSearch', term: request.term},
dataType: 'json',
cache: false,
timeout: 30000,
success: function(data) {
if(!data){
return;
}
var finalSource = $.map(data, function(m) {
return {
'name': m.configurationId.displayName,
'ext': m.extension,
'id': m.configurationId.id
};
});
response(finalSource);
}
});
},
focus: function() {
// prevent value inserted on focus
//return false;
},
select: function( event, ui ) {
console.log(ui.item);
alert(ui.item.value + ' < > ' + ui.item.label + ' was selected!!!');
}
})

Related

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 ?

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 'Disable' show all terms

Hey could someone guide me out of this problem....
I successfully created the jquery autocomplete function , but my problem is that autocomplete suggestions shows all the available labels . Autocomplete is showing the results which are not even matching the search term . I mean it showing all available label . Is their any solution to show only matching labels. here is the java function.
Any help will be gladly appreciated . Thank You
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response( $.map( data.stuff, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
EDIT : - Here is the Json File
{"stuff":[ {"label" : "Dragon", "value" : "eg.com"} ,
{"label" : "testing", "value" : "eg2.com"}]}
Successful Edited Code
<script>
$(document).ready(function () {
$("#search-title").autocomplete({
source: function ( request, response ) {
$.ajax({
url: "availabletags.json",
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
var re = new RegExp( request.term, "i" );
return re.test( v.label );
});
response( $.map( sData, function ( item ) {
return {
label: item.label,
value: item.value
};
}));
}
});
},
minLength: 2,
focus: function (event, ui) {
this.value = ui.item.label;
event.preventDefault(); // Prevent the default focus behavior.
},
select: function (event, ui) {
$(event.target).val(ui.item.label);
window.location = ui.item.value;
return false;
}
});
});
</script>
Here is the change you want to make:
dataType: "json",
success: function (data) {
var sData = data.stuff.filter(function(v) {
return v.value.indexOf( request.term ) > -1;
});
response( $.map( sData, function ( item ) {
This search will be done by value. To search by label, in other words for the user's input to be compared to the label in your JSON use the following instead:
return v.label.indexOf( ........
UPDATE
To make your search case insensitive, use the following:
var re = new RegExp( request.term, "i" );
return re.test( v.label );
instead of return v.value.indexOf( request.term ) > -1;

search matching keyword on typing anything

Iam new to programming.
Please dont mind if its a simple question.
I have a search box,
html
<input type="text" id="search" placeholder="Search" autocomplete="off"/>
When i type anything in search box, for example like abc, I need to show in dropdown as , restaurents matching 'abc', this is to be done in frontend.
Here is the code i have written to get data,
js
$("#search").keyup(function(){
if ($(this).val().length == 3) {
console.log($(this).closest(".row-fluid").find("ul").attr('id'));
$(this).closest(".row-fluid").find("ul").css('display', 'none');
}
}).autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/search/site_search/"+$('#search').val(),
dataType: "json",
success: function(data) {
response( $.map( data.result, function( item ) {
return {
label: item.complaint_title,
value: item.complaint_iid,
};
}));
},
error: function(result) {
alert("Error");
}
});
},
select: function (event, ui) {
console.log(ui.item);
},
focus: function( event, ui ) {
$( "#search" ).val( ui.item.label );
return false;
}
}).data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "<li>" )
.data( "ui-autocomplete-item", item )
.append( "<a>" + item.label + "</a>" )
.appendTo( ul );
};
Can anyone tell me how to do this.

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