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/
Related
JQueryMobile 1.4 has deprecated the pageshow event and instead recommends using pagecontainershow; however, while I'm able to get the pagecontainershow event at a document level, I can't bind a function to a particular page.
<div id="page1" data-role="page">
...
<script>
$( "#page1" ).on( "pagecontainershow", function( event, ui ) {
console.log("page1 pagecontainershow");
} );
</script>
</div>
Demonstration: http://jsbin.com/IFolanOW/22/edit?html,console,output
I also considered using the alternative form of the jQuery "on" function where we use a selector, but that would need to be a parent of the page div, and that might include other pages, so that doesn't work.
As a workaround, I've done this, but it is very inefficient:
function registerOnPageShow(pageId, func) {
var strippedPageId = pageId.replace("#", "");
var e = "pagecontainershow." + strippedPageId;
// TODO why isn't it working to use $(pageId) instead of $(document)?
$( document ).off(e).on(e, null, {page: strippedPageId, f: func}, function(e, ui) {
if ($(":mobile-pagecontainer").pagecontainer("getActivePage")[0].id == e.data.page) {
e.data.f(e, ui);
}
});
}
You can get the page ID like this.
$(document).on('pagecontainershow', function(e, ui) {
var pageId = $('body').pagecontainer('getActivePage').prop('id');
});
There is currently no way to have a show/hide event on a specific page.
Here is what I'm using (jqmobile >1.4):
$(document).on("pagecontainershow", function () {
var activePage = $.mobile.pageContainer.pagecontainer("getActivePage");
var activePageId = activePage[0].id;
switch (activePageId) {
case 'loginPage':
...
break;
case 'homePage':
...
break;
case 'groupPage':
...
break;
default:
}
});
$(document).on("pagecontainershow", function(event, ui) {
var pageId = $('body').pagecontainer('getActivePage').prop('id'),
showFunc = pageId+'_show';
if (typeof MobileSite[showFunc] == 'function') {
MobileSite[showFunc]();
}
});
MobileSite is contained in an external .js file with all the show() functions.
$(document).on("pagecontainerbeforeshow", function (event, ui) {
if (typeof ui.toPage == "object") {
var crrentPage = ui.toPage.attr("id")
}
});
and you must use this code before calling Index.js !!
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
}
},
edit A: this is NOT a jquery question, but rather a jquery Mobile question.
edit B: I changed the title ... originally I asked how to fire 'click' event specifically, but apparently the 'click' event is not the proper event to use if you want to re-create a jqm:Select Menu choice.
how to programatically fire an event on a jquery mobile select menu?
<select id = 'my_select'
name = 'my_select'
onchange = 'gf_handle_change( this.value );' >
<option id = 'option_A' value = 'A'> A </option>
<option id = 'option_B' value = 'B'> B </option>
</select>
<script>
function gf_fire_event( args_val )
{ alert( 'test : ' + jQuery( '#option_' + args_val ) ) ;
jQuery( '#option_' + args_val ).trigger( 'click' ) ;
}
function gf_handle_change( args_val )
{ alert( args_val ) ;
}
gf_fire_event( 'A' ) ;
</script>
This does not work.
Here's an example:
$(document).on('pagebeforeshow', '#index', function(){
$("#test-button").on( "click", function(event, ui) {
$('#my_select option#option_B').trigger('click');
});
$("#my_select option").each(function(){
$(this).on( "click", function(event, ui) {
$(this).attr('selected' , true);
$('#my_select').selectmenu('refresh');
});
});
});
Working jsFiddle example: http://jsfiddle.net/Gajotres/RZ68b/
One more thing, do not use onclick="... or onchange="... with jQuery Mobile, this could case problems with event triggering. Always bind your event programatically.
That will do it
function gf_fire_event( args_val )
{
//Select an option
$('#my_select option[value=' + args_val +']').attr("selected", "selected");
//Refresh jQM select menu
$('#my_select').selectmenu('refresh');
//Trigger change event
$('#my_select').trigger('change');
}
See working jsFiddle
How the new jQueryUI's tooltip widget can be modified to open the tooltip on click event on certain element's on document, while the others are still showing their tootip on mouseover event. In click-open case the tooltip should be closed by clicking somewhere else on the document.
Is this possible at all?
Using jqueryui:
HTML:
<div id="tt" >Test</div>
JS:
$('#tt').on({
"click": function() {
$(this).tooltip({ items: "#tt", content: "Displaying on click"});
$(this).tooltip("open");
},
"mouseout": function() {
$(this).tooltip("disable");
}
});
You can check it using
http://jsfiddle.net/adamovic/A44EB/
Thanks Piradian for helping improve the code.
This code creates a tooltip that stays open until you click outside the tooltip. It works even after you dismiss the tooltip. It's an elaboration of Mladen Adamovic's answer.
Fiddle: http://jsfiddle.net/c6wa4un8/57/
Code:
var id = "#tt";
var $elem = $(id);
$elem.on("mouseenter", function (e) {
e.stopImmediatePropagation();
});
$elem.tooltip({ items: id, content: "Displaying on click"});
$elem.on("click", function (e) {
$elem.tooltip("open");
});
$elem.on("mouseleave", function (e) {
e.stopImmediatePropagation();
});
$(document).mouseup(function (e) {
var container = $(".ui-tooltip");
if (! container.is(e.target) &&
container.has(e.target).length === 0)
{
$elem.tooltip("close");
}
});
This answer is based on working with different classes. When the click event takes place on an element with class 'trigger' the class is changed to 'trigger on' and the mouseenter event is triggered in order to pass it on to jquery ui.
The Mouseout is cancelled in this example to make everything based on click events.
HTML
<p>
<input id="input_box1" />
<button id="trigger1" class="trigger" data-tooltip-id="1" title="bla bla 1">
?</button>
</p>
<p>
<input id="input_box2" />
<button id="trigger2" class="trigger" data-tooltip-id="2" title="bla bla 2">
?</button>
</p>
jQuery
$(document).ready(function(){
$(function () {
//show
$(document).on('click', '.trigger', function () {
$(this).addClass("on");
$(this).tooltip({
items: '.trigger.on',
position: {
my: "left+15 center",
at: "right center",
collision: "flip"
}
});
$(this).trigger('mouseenter');
});
//hide
$(document).on('click', '.trigger.on', function () {
$(this).tooltip('close');
$(this).removeClass("on")
});
//prevent mouseout and other related events from firing their handlers
$(".trigger").on('mouseout', function (e) {
e.stopImmediatePropagation();
});
})
})
http://jsfiddle.net/AK7pv/111/
I have been playing with this issue today, I figured I would share my results...
Using the example from jQueryUI tooltip, custom styling and custom content
I wanted to have a hybrid of these two. I wanted to be able to have a popover and not a tooltip, and the content needed to be custom HTML. So no hover state, but instead a click state.
My JS is like this:
$(function() {
$( document ).tooltip({
items: "input",
content: function() {
return $('.myPopover').html();
},
position: {
my: "center bottom-20",
at: "center top",
using: function( position, feedback ) {
$( this ).css( position );
$( "<div>" )
.addClass( "arrow" )
.addClass( feedback.vertical )
.addClass( feedback.horizontal )
.appendTo( this );
}
}
});
$('.fireTip').click(function () {
if(!$(this).hasClass('open')) {
$('#age').trigger('mouseover');
$(this).addClass('open');
} else {
$('#age').trigger('mouseout');
$(this).removeClass('open');
}
})
});
The first part is more or less a direct copy of the code example from UI site with the addition of items and content in the tooltip block.
My HTML:
<p>
<input class='hidden' id="age" />
Click me ya bastard
</p>
<div class="myPopover hidden">
<h3>Hi Sten this is the div</h3>
</div>
Bacially we trick the hover state when we click the anchor tag (fireTip class), the input tag that holds the tooltip has a mouseover state invoked, thus firing the tooltip and keeping it up as long as we wish... The CSS is on the fiddle...
Anyways, here is a fiddle to see the interaction a bit better:
http://jsfiddle.net/AK7pv/
This version ensures the tooltip stays visible long enough for user to move mouse over tooltip and stays visible until mouseout. Handy for allowing the user to select some text from tooltip.
$(document).on("click", ".tooltip", function() {
$(this).tooltip(
{
items: ".tooltip",
content: function(){
return $(this).data('description');
},
close: function( event, ui ) {
var me = this;
ui.tooltip.hover(
function () {
$(this).stop(true).fadeTo(400, 1);
},
function () {
$(this).fadeOut("400", function(){
$(this).remove();
});
}
);
ui.tooltip.on("remove", function(){
$(me).tooltip("destroy");
});
},
}
);
$(this).tooltip("open");
});
HTML
Test
Sample: http://jsfiddle.net/A44EB/123/
Update Mladen Adamovic answer has one drawback. It work only once. Then tooltip is disabled. To make it work each time the code should be supplement with enabling tool tip on click.
$('#tt').on({
"click": function() {
$(this).tooltip({ items: "#tt", content: "Displaying on click"});
$(this).tooltip("enable"); // this line added
$(this).tooltip("open");
},
"mouseout": function() {
$(this).tooltip("disable");
}
});
jsfiddle
http://jsfiddle.net/bh4ctmuj/225/
This may help.
<!-- HTML -->
Click me to see Tooltip
<!-- Jquery code-->
$('a').tooltip({
disabled: true,
close: function( event, ui ) { $(this).tooltip('disable'); }
});
$('a').on('click', function () {
$(this).tooltip('enable').tooltip('open');
});
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/