jquery ui autocomplete with autoselect plugin - jquery-ui

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
}
},

Related

jQuery UI Autocomplete on KeyPress write value

I am trying to implement jQuery UI Autocomplete the way like
when I have a list "alpha","beta","gamma" then type "a" into the input field
and only get "alpha" as proposal I want to hit enter and "alpha" shall be
the new value of the input field instead of selecting "alpha" by mouse click.
Is this possible?
$.ajax({
url : 'myAjax.php',
type : 'POST',
data : { param: getData },
dataType : 'json',
success : function(data) {
$("#myField").autocomplete({
minLength: 0,
source: data,
focus: function( event, ui ) {
$(this).val(ui.item.key);
return false;
},
select: function( event, ui ) {
$("#myField").val(ui.item.value);
return false;
}
});
}
});
you can add
autoFocus: true
this will make it focus on the first element that you get
and when you press enter it will automatically put the label in the field by using
$("#myField").val(ui.item.label);
Yes it's possible, you have to put more parameter on your autocomplete method
$( "#tags" ).autocomplete({
source: function( request, response ) {
var matcher = new RegExp( "^" + $.ui.autocomplete.escapeRegex( request.term ), "i" );
response( $.grep( data, function( item ){
return matcher.test( item.label );
}) );
},
minLength: 1,
select: function(event, ui) {
event.preventDefault();
$("#tags").val(ui.item.label);
$("#selected-tag").val(ui.item.label);
window.location.href = ui.item.value;
}
,
focus: function(event, ui) {
event.preventDefault();
$("#tags").val(ui.item.label);
}
});
see this exemple link

jquery autocomplete renderItem

I have the following code. It generates no js errors. Can't get the autocomplete to display any results:
$(function() {
$.ajax({
url: "data.xml",
dataType: "xml",
cache: false,
success: function (xmlResponse) {
var data_results = $("Entry", xmlResponse).map(function () {
return {
var1: $.trim($("Partno", this).text()),
var2: $.trim($("Description", this).text()),
var3: $.trim($("SapCode", this).text()),
var4: $("Title", this).text(),
var5: $.trim($("File", this).text()),
var6: $.trim($("ItemID", this).text())
};
}).get();
$("#searchresults").autocomplete({
source: data_results,
minLength: 3,
select: function (event, ui) {
...
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" ).data("item.autocomplete", item)
.append( "<a>" + item.var1 + "<br>" + item.var2 + "</a>")
.appendTo( ul );
};
}
});
Any ideas what I might be missing? Thanks in advance.
It seems that .data('autocomplete') is now .data('ui-autocomplete').
Source: http://jqueryui.com/upgrade-guide/1.10/#removed-data-fallbacks-for-widget-names
By default, autocomplete expects your source array to contain objects with either a label property, a value property, or both.
With that in mind you have two options:
Add a label or value property to your source objects when you process the array from your AJAX call:
var data_results = $("Entry", xmlResponse).map(function () {
return {
var1: $.trim($("Partno", this).text()),
var2: $.trim($("Description", this).text()),
var3: $.trim($("SapCode", this).text()),
var4: $("Title", this).text(),
var5: $.trim($("File", this).text()),
var6: $.trim($("ItemID", this).text()),
value: $.trim($("Description", this).text())
};
}).get();
The value you assign will be used on focus, select, and to search on.
Change the source function to perform custom filtering logic:
$("#searchresults").autocomplete({
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response($.grep(data, function (value) {
return matcher.test(value.var1) ||
matcher.test(value.var2);
/* etc., continue with whatever parts of the object you want */
}));
},
minLength: 3,
select: function (event, ui) {
event.preventDefault();
this.value = ui.var1 + ui.var2;
},
focus: function (event, ui) {
event.preventDefault();
this.value = ui.var1 + ui.var2;
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
return $( "<li></li>" ).data("item.autocomplete", item)
.append( "<a>" + item.var1 + "<br>" + item.var2 + "</a>")
.appendTo( ul );
};
Note that with this strategy you have to implement custom select and focus logic.

jquery ui autocomplete pass a variable

I m using jquery UI for getting suggestions of friend names and id, but the problem is I am not able to pass user id using autocomplete json function .
$(function() {
function split( val ) {
return val.split( /,\s*/ );
}
function extractLast( term ) {
return split(term).pop();
}
$( "#recipient" )
// don't navigate away from the field on tab when selecting an item
.bind( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).data( "autocomplete" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
var attm= $('.USERID').val();
$.getJSON( "modules/messages/sql.php", {
term: extractLast( request.term ),
}, response );
},
search: function() {
// custom minLength
var term = extractLast( this.value );
if ( term.length < 2 ) {
return false;
}
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
var prollNos = $('#recipientid').val()
$('#recipientid').val(prollNos + ui.item.id + ", ");
return false;
}
});
});
in which i am trying to pass a: $('.USERID').val() as user id , can anyone help me out?
I achieve something similar by GET. I use jquery-ui-autocomplete, as source I use: "source.php?param=something". So the final request my source page gets is "source.php?param=something&term=blabla"

Jquery UI autocomplete IE 7 issue

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

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