I have a jQuery autocomplete input box for time. It lists all available times by 15 minute increments starting at 12:00 AM. I’d like to display all results, but have the time closest to now selected. Is there a way to do this?
Here’s what I have so far:
var j$ = jQuery.noConflict();
function log(item) { if(j$.browser.mozilla) { console.log(item); } }
function init()
{
var times = [];
for (var i=0;i<24;i++) {
for (var j=0;j<4;j++) {
var hour = (i>12?(i-12)+"":(i==0?"12":i)+"");
var mins = "00"; var AMPM = (i>12?" PM":" AM");
if(j==0) { mins="00"; }
if(j==1) { mins="15"; }
if(j==2) { mins="30"; }
if(j==3) { mins="45"; }
times.push(hour+":"+mins+AMPM);
}
}
// initialize the autocompletes
j$("#time")
.autocomplete({
source: times,
minLength: 0,
delay: 0,
autoFocus: true
})
.bind("focus",function(){
j$(this).autocomplete("search","");
});
}
j$(document).ready(init);
Update
I added a jsFiddle for the above code.
You can accomplish this with the
openevent and some trickery with the underlyingmenuwidget that autocomplete uses:Example: http://jsfiddle.net/DmJup/
There are some areas for improvement here, such as refactoring the code in
openinto several methods.I think allowing an option (via a plugin) that would let you specify a function to determine the option to select would be useful.