Jquery UI autocomplete IE 7 issue - jquery-ui

I am using jquery UI autocomplete. It works in all other browsers FF, Chrome etc except IE7. Works for higher versions of IE as well but IE7 gives the below error:
SCRIPT3: Member not found.
jquery.min.js, line 2 character 30636
This is my function:
$('input.autocomplete').each( function() {
var $input = $(this);
// Set-up the autocomplete widget.
var serverUrl = $input.data('url');
$(this).autocomplete({
source: function( request, response ) {
var countrySelect = $("#countrySelect").val();
if($input.attr('id') == 'searchJobPostalCode'){
countrySelect = $("#searchJobCountrySelect").val();
}else if($input.attr('id') == 'searchPeoplePostalCode'){
countrySelect = $("#searchUserCountrySelect").val();
}
$.ajax({
url: serverUrl,
dataType: "json",
data: {
term: request.term,
countrySelect: countrySelect
},
success: function( data ) {
$input.removeClass( "ui-autocomplete-loading" );
response( $.map( data, function( item ) {
if(typeof item.companyName != 'undefined'){
return {
label: item.companyName,
value: item.companyName,
id: item.companyID
}
}
if(typeof item.locationId != 'undefined'){
return {
label: item.postalCode +','+item.placeName+','+item.adminName1+','+item.countryCode,
value: item.postalCode +','+item.placeName+','+item.adminName1+','+item.countryCode,
postalCode: item.postalCode,
city: item.placeName,
state: item.adminName1,
country: item.countryCode
}
}
//to show user alias autocomplete on compose message
if(typeof item.userAlias != 'undefined'){
var label1 = item.userAlias;
if(typeof item.city != 'undefined'){
label1 = label1+','+item.city;
}
if(typeof item.state != 'undefined'){
label1 = label1+','+item.state;
}
if(typeof item.country != 'undefined'){
label1 = label1+','+item.country;
}
return {
label: item.userAlias,
userAlias: item.userAlias
}
}
}));
}
});
},
minLength: 3,cacheLength:0,keyDelay:900,
select: function( event, ui ) {
$("#companyId").val(ui.item.id);
if(typeof ui.item.userAlias != 'undefined'){
$(".toUser").val(ui.item.userAlias);
}
if(typeof ui.item.postalCode != 'undefined'){
$("#postalCode").val(ui.item.postalCode);
$("#city").val(ui.item.city);
$("#state").val(ui.item.state);
$("#country").val(ui.item.country);
if($input.attr('id') == 'searchJobPostalCode'){
$("#searchPostalCodeJobsSearch").val(ui.item.postalCode);
$("#searchCityJobsSearch").val(ui.item.city);
$("#searchStateJobsSearch").val(ui.item.state);
$("#searchCountryJobsSearch").val(ui.item.country);
}else if($input.attr('id') == 'searchPeoplePostalCode'){
$("#searchPostalCodePeople").val(ui.item.postalCode);
$("#searchCityPeople").val(ui.item.city);
$("#searchStatePeople").val(ui.item.state);
$("#searchCountryPeople").val(ui.item.country);
}
}
},
change: function( event, ui ) {
if($(this).attr('id') !='companyName'){
if ( ui.item == null) {
valid = false;
}else{
valid = true;
}
if ( !valid ) {
// remove invalid value, as it didn't match anything
$( this ).val( "" );
select.val( "" );
input.data( "autocomplete" ).term = "";
return false;
}
}
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
$( this ).removeClass( "ui-autocomplete-loading" );
}
});
});
I tried to debug and it errors out at line : $(this).autocomplete({
Any idea? Thanks in advance

Looks like the problem is with my OS. I had installed Windows 8 consumer preview and was running IE using dev tools in IE7 compatibility. It works in windows 7. thanks.

My guess is that one of the scripts is not loading properly. This happened to me once, with jquery and IE 7. Here's how I solved the issue:
In the HTML, BEFORE all of your script tags, add this:
<script type="text/javascript"></script><!--this is here because of an IE bug-->
When I included that line before my tag for jquery.min.js, the problem went away.
IE7 is a frustration.

I resolved with change ui version. Now I use 1.9.1.custom.min.js (before was jquery UI 1.8) and it work with IE7 compatibility. I use jquery v1.7.2

Related

How to use Jquery autocomplete with the backend couchDb

So far I've used Jquery autocomplete for backend php. But I want to use jquery auto complete to fetch records from couchdb. Can anyone please help me.
Or is there any other way to achieve autocomplete with couchDB
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$("#search_name").autocomplete({
source: function( request, response ) {
$.couch.db("db1").view("Views/testPatients", {
success: function(data) {
response(data.rows);
},
error: function(status) {
console.log(status);
},
key: request.term
});
},
minLength: 3,
focus: function(event, ui) {
console.log(ui.item.key);
$("#search_name").val(ui.item.key);
return false;
},
select: function( event, ui ) {
$("#search_name").val(ui.item.key);
return false;
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
}).
data("uiAutocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.key + "</a>")
.appendTo(ul);
};

jquery ui autocomplete with autoselect plugin

I am using a jquery ui autocomplete. when the user types in their own value, rather than selecting an item from the list, the textbox clears. This is ok (I don't want the user to be able to enter their own values) except if the user types in a value that does exist on the list.
I tried using the autoSelect plugin as detailed in this post, but it is not working - I added the plugin but when I type in a value that IS on the list and hit tab, I get the same results as before - the textbox clears.
Here is my autocomplete:
$(function () {
$('[id$="txtDocType').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/MyPage.aspx/myFunction",
data: "{'prefixText':'" + request.term.toLowerCase() + "', 'ddvId':'" + this.element.data('autocomplete') + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) { }
});
},
minlength: 1,
select: function (event, ui) {
$('#divOtherFields input[type=text], input[type=password]').prop("disabled", false).removeClass("disabled");
$('[id$="btnSaveNext"],[id$="btnSaveClose"]').prop("disabled", false);
$('[id$="txtReceiptDate"]').datepicker("setDate", new Date());
}
});
});
Here is the plugin:
(function( $ ) {
$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).on( "blur", function( event ) {
var autocomplete = $( this ).data( "autocomplete" );
if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( $(this).val() ) + "$", "i" );
autocomplete.widget().children( ".ui-menu-item" ).each(function() {
var item = $( this ).data( "item.autocomplete" );
if ( matcher.test( item.label || item.value || item ) ) {
autocomplete.selectedItem = item;
return false;
}
});
if ( autocomplete.selectedItem ) {
autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
}
});
}( jQuery ));
I set a breakpoint in the plugin on this line - "$( ".ui-autocomplete-input" ).on( "blur", function( event )" and the breakpoint was hit, yet the code would not step through. When I set a breakpoint to this line - "var autocomplete = $( this ).data( "autocomplete" );" the breakpoint was NOT hit.
Any ideas? I am at my wits end with this.
I solved this by making a couple of tweaks to the autoSelect plugin. Here is the code that eventually worked for me:
$(".ui-autocomplete-input").bind("focusout", function (event) {
var autocomplete = $(this).data("ui-autocomplete");
if (!autocomplete.options.autoSelect || autocomplete.selectedItem) { return; }
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i");
autocomplete.widget().children(".ui-menu-item").each(function () {
var item = $(this).data("ui-autocomplete-item");
if (matcher.test(item.label || item.value || item)) {
autocomplete.selectedItem = item;
return false;
}
});
if (autocomplete.selectedItem) {
autocomplete._trigger("select", event, { item: autocomplete.selectedItem });
}
});
I used the focus event to set the first value to a hidden variable. The same hidden variable also got updated in the select event. And then this was the hidden variable which I posted to the ajax call.
Why I did not use focus to set the value in the autocomplete input box, was because doing so populated the autocomplete input box even while I was typing in this box.
focus: function (event, ui) {
if($("#streetid")) $("#streetid").val(ui.item.label); //this was my hidden variable
}
},

JQuery UI autocomplete select on blur or on close

I would like to select the value from my input autocomplete on blur or on close.
I tried to put this in the function of the close parameter but it can't work :
close: function() {
$($(this).data('autocomplete').menu.active).find('a').trigger('click');
$(this).removeClass('ui-corner-top').addClass('ui-corner-all');
}
Anybody has a clue ?
Ok, thanks to Andrew Whitaker, I got this solution to select the first value automatically when leaving the autocompletion :
$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).live( "blur", function( event ) {
var autocomplete = $( this ).data( "autocomplete" );
if ( !autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }
autocomplete.widget().children( ".ui-menu-item:first" ).each(function() {
var item = $( this ).data( "item.autocomplete" );
autocomplete.selectedItem = item;
});
if ( autocomplete.selectedItem ) {
autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
}
});
Updated code for jQuery UI - v1.12.1
$.ui.autocomplete.prototype.options.autoSelect = true;
$( ".ui-autocomplete-input" ).live( "blur", function( event ) {
var autocomplete = $(this).autocomplete('instance');
if (!autocomplete.options.autoSelect || autocomplete.selectedItem ) { return; }
autocomplete.widget().children( ".ui-menu-item:first" ).each(function() {
var item = $( this ).data('ui-autocomplete-item');
autocomplete.selectedItem = item;
});
if ( autocomplete.selectedItem ) {
autocomplete._trigger( "select", event, { item: autocomplete.selectedItem } );
autocomplete._value( autocomplete.selectedItem.value );
}
});

add image to jQuery UI autocomplete remote source with cache

I am using jQuery autocomplete remote source with caching. As per demo by jQUery UI website javascript of remote source with caching is
<script>
$(function() {
var cache = {},
lastXhr;
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response( cache[ term ] );
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
cache[ term ] = data;
if ( xhr === lastXhr ) {
response( data );
}
});
}
});
});
</script>
Now I want to add some code to above javascript to display image in autocomplete list. There is an excellent example for displaying image in jQuery autocomplete such as:
http://jsfiddle.net/3zSMG/ but it does not include caching part.
I have been trying but NOT able to integrate this example into the existing remote with caching javascript. Any help would be very much appreciated. Many thanks.
FOLLOW-UP: As suggested by Andrew Whitaker, I have updated my script as follow:
<script>
$(function() {
var cache = {},
lastXhr;
$( "#birds" ).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
if ( term in cache ) {
response(cache[term]);
return;
}
lastXhr = $.getJSON( "search.php", request, function( data, status, xhr ) {
var results;
if ( xhr === lastXhr ) {
results = $.map(data, function(item) {
return {
value: item.value,
avatar: item.avatar
};
});
cache[term] = results;
response(results);
}
});
},
}).data("autocomplete")._renderItem = function (ul, item) {
if ( item.value != null ) {
if ( item.avatar != null) {
return $("<li/>")
.data("item.autocomplete", item)
.append("<a><img src='images/" + item.avatar + "' />" + item.value + "</a>")
.appendTo(ul);
}
else {
return $("<li/>")
.data("item.autocomplete", item)
.append("<a>" + item.value + "</a>")
.appendTo(ul);
}
}
};
});
And content of search.php:
<?php
require_once "config.php";
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends
$qstring = "select id, subject as value, avatar from Suggests where subject LIKE '%".$term."%'";
$result = mysql_query($qstring);//query the database for entries containing the term
while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
$row['value']=htmlentities(stripslashes($row['value']));
$row['id']=(int)$row['id'];
$row['avatar']=$row['avatar'];
$row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
?>
I am able to see images in autocomplete list. But there is an issue: After keying in few letters, autocomplete list is shown up, if I continue adding some more random letters to expect autcomplete list to disappear (because the userinput no longer matches) but it does not. Andrew's example work well. Is there anything wrong with my javascript? Trying to debug by Firebug, I got error: TypeError element is null.
The key to the image portion of the demos is overriding the _renderItem function to change the li's that are generated to suggest items. This usually means that your source is an array with objects that have a label and/or value property, as well as a property that allows you to display the image correctly inside of _renderItem.
The caching code just stores the search term and results in a hash and looks in that hash before hitting the server.
Using the JSFiddle you linked as an example, here's something using StackOverflow's API that does caching and images:
$(document).ready(function() {
var cache = {},
lastXhr;
$("#auto").autocomplete({
source: function(request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
lastXhr = $.ajax({
url: "http://api.stackoverflow.com/1.1/users",
data: {
filter: request.term,
pagesize: 10
},
jsonp: "jsonp",
dataType: "jsonp",
success: function(data, status, xhr) {
var results;
if (xhr === lastXhr) {
results = $.map(data.users, function(el, index) {
return {
value: el.display_name,
avatar: "http://www.gravatar.com/avatar/" + el.email_hash
};
});
cache[term] = results;
response(results);
}
}
});
},
delay: 500
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li />")
.data("item.autocomplete", item)
.append("<a><img src='" + item.avatar + "' />" + item.value + "</a>")
.appendTo(ul);
};
});​
Notes:
This example is more complex than the examples on jQueryUI's website because the data from the API has to be transformed (to have avatar/value properties). The important thing to note is that we're caching the received values after the $.map call transforms the result array.
This looks complicated but just remember the two guidelines at the top of the answer and you should be good.
Example: http://jsfiddle.net/rK7TS/
Here's what I did:
lastXhr = $.getJSON( action, request, function( data, status, xhr ) {
if( data && data !== null ) {
var results;
if( xhr === lastXhr ) {
results = $.map(data, function(item) {
return {
value: item.value,
avatar: item.avatar
};
});
cache[term] = results;
response(results);
}
} else {
response([{ value: 'No results found.', avatar: null}]);
}
});

jQuery UI autocomplete, show something when no results

I have the following code:
// Autocomplete search
$("#shop_search").autocomplete({
source: '<%= spotify_search_path(:json) %>',
minLength: 1,
select: function(event, ui) {
append_place(ui.item.name, ui.item.id, ui.item.shop_type, ui.item.address_geo, ui.item.contact, ui.item.email, ui.item.web);
$("#shop_search").val('');
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + "<span class='autocomplete_link'>" + item.name + "</span>" + "<br />" + "<span class='autocomplete_address'>" + item.address_geo + "</span>" + "</a>" )
.appendTo( ul );
$(".ui-autocomplete-loading").ajaxStart(function(){
$(this).show();
});
$(".ui-autocomplete-loading").ajaxStop(function(){
$(this).hide();
});
};
Currently it only shows the drop down autocomplete when there is search result. I want it to show "No matches found" when nothing could be found. What should I add into the code?
Thanks.
If you use a jQuery ajax call for the source, you can append "No results found" to the results if there aren't any. Then on the select method, you can simply check to see if the item is the "no results found" item that you added and if so, do nothing. Here I identified that by checking to see if the id was equal to zero.
$("#shop_search").autocomplete({
source: function (request, response) {
$.ajax({
url: "<%= spotify_search_path(:json) %>",
data: {
term: request.term
},
success: function (data) {
if (data.length == 0) {
data.push({
id: 0,
label: "No results found"
});
}
response(data);
}
});
},
select: function (event, ui) {
if (ui.item.id != 0) {
append_place(ui.item.name, ui.item.id, ui.item.shop_type, ui.item.address_geo, ui.item.contact, ui.item.email, ui.item.web);
$("#shop_search").val('');
}
}
});
You'll need to do some work on your template to get the "no results found" to display properly, but this should get you on the right track.
You can just check if item is null or 0.
If item is 0 or null append "No matches found" else append the item. That's basically the whole logic.
May be this helps
source: function( request, response ) {
$.getJSON( url, {
term: extractLast( request.term )
}, response )
.error(function() {
console.log("no results");
});
},
$( "#jsonNameSearch" ).autocomplete({
// This is the source of the autocomplete, in the success method if the
// length of the response is zero then highlight the field indicating no match.
source: function( request, response ) {
$.getJSON( 'jsonAutocomplete.ajax?dataType=drivers', {
term: request.term
}, response )
.success(function(data) {
(data.length == 0) ? $( "#jsonNameSearch" ).addClass('nomatch') : $( "#jsonNameSearch" ).removeClass('nomatch');
});
},
select: function( event, ui ) {
if (ui.item) self.location.replace('driverModify.htm?id='+ui.item.id);
}
});

Resources