How to use Jquery autocomplete with the backend couchDb - jquery-ui

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

Related

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

passing parameters to jquery ui dialog

I use .data like this to pass the id of the textbox that calls the dialog
$("#<%=txtDirProprio.ClientID%>").focus(function()
{
$("#<%=dialog.ClientID%>").dialog( "open" ).data("id","#<%=txtDirProprio.ClientID%>");
return false;
});
here is the code for the dialog
$("#<%=dialog.ClientID%>").dialog({
autoOpen: false,
show: "blind",
hide: "explode",
width: 800,
height:200,
modal: true,
buttons:
{
"Ajouter": function() {
$( this ).dialog( "close" );
StringBuilderDir($( this ).data("id"));
},
"Vider": function() {
$( this ).dialog( "close" );
$( $( this ).data("id") ).val("")
},
"Canceler": function() {
$( this ).dialog( "close" );
}
},
open: function()
{
var dir = $( $( this ).data("id") ).val().split("-");
if(dir[0] != "")
{
$("#<%=dd_dialog_directionvp.ClientID%> option").each(function(index)
{
if ($("#<%=dd_dialog_directionvp.ClientID()%> option")[index].text == dir[0])
{
$("#<%=dd_dialog_directionvp.ClientID()%> option")[index].selected = true;
}
})
}
}
});
So $ ( this ).data("id") returns the id of the textbox. It works fine except in the open function. The id is undefined
Why it works in the functions for the buttons but not in the open function. It looks like it's not the same 'this'
Thank you
$("#<%=txtDirProprio.ClientID%>").focus(function()
{
$("#<%=dialog.ClientID%>").data("id","#<%=txtDirProprio.ClientID%>").dialog( "open" );
return false;
});
Have to set the data first before calling .dialog('open');

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