Mornin' all,
I have troubles to play with jQuery UI autocomplete widget events.
I want to a add a custom class to the parent <li> of the selected item.
The generated markup looks like :
<li class="result">
<a><span></span></a>
</li>
When an item is focus, jQuery add the class .ui-state-hover to the <a>
How can I add a class .selected to the parent <li> ?
I'm trying to do it from a focus event but I don't know how to access to the parent <li>.
I looked to the source of jQuery UI and found where and how the .ui-state-hover is applied but doesn't help.
Here is my code for autocomplete.
/**
* Override the default behavior of autocomplete.data('autocomplete')._renderItem.
*
* #param ul _object_ The conventional ul container of the autocomplete list.
* #param item _object_ The conventional object used to represent autocomplete data.
* {value:'',label:'',desc:'',icon:''}
*/
var renderItemOverride = function (ul, item) {
return $('<li class="result"></li>')
.data("item.autocomplete", item)
.append('<a><span class="name">' + item.label + '</span><span class="type"></span></a>')
.appendTo(ul);
};
$('#live_search').autocomplete({
source: function(request, response) {
$.ajax({
url: "search.json",
dataType: "json",
cache: false,
data: {
term: request.term
},
success: function(data ) {
response($.map(data.contacts, function(item) {
return {
label: item.name || (iterm.firstname + item.lastname),
value: item.name || (iterm.firstname + item.lastname),
id: item._id
}
}));
}
});
},
appendTo: '.live_search_result_list',
autoFocus: true,
minLength: 2,
focus: function(event, ui) {
},
select: function(event, ui) {
console.log("do a redirection");
}
}).data('autocomplete')._renderItem = renderItemOverride;
})
Any ninja can help ?
How about:
focus: function(event, ui) {
$(".live_search_result_list li.result").removeClass("selected");
$("#ui-active-menuitem")
.closest("li")
.addClass("selected");
},
Then, to remove the selected class from any lis when the menu loses mouse focus:
$(".live_search_result_list ul").mouseleave(function() {
$(this).children("li.result").removeClass("selected");
});
Here's a working example: http://jsfiddle.net/andrewwhitaker/4z3SQ/
Related
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
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
}
},
I'm using jquery ui tabs with the tablesorter 2.0 plugin to obtain sort abilities on a dynamically populated html table but the sort only happens on the first tab upon page load. The other tabs do not sort or obtain the zebra striping form the tablesorter.
html:
<div id="tabs">
<ul>
<li>Ftp Only</li>
<li>Billing Only</li>
<li>Variance</li>
<li>Adj Only</li>
</ul>
</div>
I've tried:
$('#tabs').tabs({
ajaxOptions: {cache: false},
load: function()
{
$("#ReportTable").tablesorter();
}
});
Any suggestions are much appreciated.
The zebra widget only applies to visible rows, so you'll need to trigger the applyWIdgets method. And I'm going to assume you are using jQuery UI 1.10.2 and jQuery 2.0, where you can use the activate callback (demo):
$("#tabs").tabs({
activate: function (event, ui) {
var $t = ui.newPanel.find('table');
// make sure there is a table in the tab
if ($t.length) {
if ($t[0].config) {
// update zebra widget
$t.trigger('applyWidgets');
} else {
// initialize tablesorter
$t.tablesorter({
theme: 'blue',
widgets: ["zebra"]
});
}
}
}
});
Update: Oops, if the table is in the first tab, use this code (demo):
var tablesorterOptions = {
theme: 'blue',
widgets: ["zebra"]
};
$("#tabs").tabs({
create: function (event, ui) {
var $t = ui.panel.find('table');
if ($t.length) {
$t.tablesorter(tablesorterOptions);
}
},
activate: function (event, ui) {
var $t = ui.newPanel.find('table');
if ($t.length) {
if ($t[0].config) {
$t.trigger('applyWidgets');
} else {
$t.tablesorter(tablesorterOptions);
}
}
}
});
I'm trying to figure out how to make an "opposite" of a jquery ui select. When someone does not select an option and just types "jquery something" output will be:
"new input: jquery something". However when the "jquery" is selected it would be nice to somehow only have "selected from list: jquery", and prevent the keypress propogation. However, both events fire. I'm trying to make it one or the other.
<input class="test" type="text" />
<script>
$('.test').autocomplete({
select: function (event, ui) {
alert('selected from list: ' + ui.item.label);
event.preventDefault();
return false;
},
source: ["jquery", "jquery ui", "sizzle"]
});
$('.test').live('keypress', function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
alert('new input: ' + $(this).val());
}
});
</script>
This is going with the assumption that the "enter" key is used to select an option from the ui's menu.
You could accomplish this using the autocompletechange event. Using this event, you can determine if the user selected an option or typed something in that wasn't on the list:
$("#auto").autocomplete({
source: ['hi', 'bye', 'foo', 'bar'],
change: function(event, ui) {
console.log(this.value);
if (ui.item == null) {
$("span").text("new item: " + this.value);
} else {
$("span").text("selected item: " + ui.item.value);
}
}
});
Example: http://jsfiddle.net/Ne9FH/
Hi I have a JQuery Ui (jquery-ui-1.8.13.custom.min.js) inside a Dialog. When I start typing on the box I get the dropdown of items but it hides right away? Does anyone know why? Here is my code:
$(".openDialog").live("click", function (e) {
e.preventDefault();
var itemId = $(this).attr("data-item-id");
var ajaxurl = $(this).attr('data-ajax-refresh-url');
var dialogId = $(this).attr("data-dialog-id");
$('<div><img src="Content/images/spinner.gif" /> Loading...</div>')
.addClass("dialog")
.attr("id", $(this).attr("data-dialog-id"))
.appendTo("body")
.dialog({
width: 'auto',
title: $(this).attr("data-dialog-title"),
buttons: {
"Save": function () {
$(this).find('form').submit();
},
close: function () {
if (typeof itemId != "undefined") {
$.get(ajaxurl, { id: itemId },
function (data) {
// The data returned is a table <tr>
$("#Row" + itemId).replaceWith(data);
});
bindConfirm();
}
$(this).remove();
}
},
modal: true
}).load(this.href, function () {
$(this).find("input[data-autocomplete]").autocomplete({ source: $(this).find("input[data-autocomplete]").attr("data-autocomplete") });
});
});
They also had problems in early 1.8 releases. I remember applying a custom CSS selector to increase zIndex manually.
See also: http://forum.jquery.com/topic/autocomplete-inside-a-dialog-1-8rc2