I have an HTML select element:
<select id='poetslist'>
<option value="shakespeare">William Shakespeare</option>
<option value="milton">John Milton</option>
<option value="keats">John Keats</option>
<option value="wordsworth">William Wordsworth</option>
<option value="larkin">Phillip Larkin</option>
</select>
In Chrome, when the page loads, the William Shakespeare
option is selected. If the user starts typing 'Phil', the list focusses itself on Phillip Larkin
. Familiar behaviour.
What I'd like to do (preferably using jQuery) is also allow the user to type the initials of the poet and have the relevant option come into focus.
So if you typed JK
, then the John Keats
option should come into focus. JM
and John Milton, etc.
I don't even know how the HTML select element works, whether it's different in different browsers, etc - and it seems to be hard to find good documentation for this.
Can anyone figure out a smart way to do this in jQuery?
Here is a complete solution:
.data()
.HTML
<select id="poetslist">
<option value="shakespeare" data-initial="WS">William Shakespeare</option>
<option value="milton" data-initial="JM">John Milton</option>
<option value="keats" data-initial="JK">John Keats</option>
<option value="wordsworth" data-initial="WW">William Wordsworth</option>
<option value="larkin" data-initial="PL">Phillip Larkin</option>
</select>
Javascript
var timer = null, initials = "";
$("#poetslist").keypress(function (e) {
initials += String.fromCharCode(e.which).toUpperCase();
// Look for option with initials beginning with the typed chars
$(this).find("option").filter(function () {
return $(this).data("initial").toUpperCase().indexOf(initials) === 0;
}).first().attr("selected", true);
// Set/reset timer
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
timer = null;
initials = "";
}, 2000); // Max 2 second pause allowed between key presses
return false;
});
With @Charlie's answer in mind, if you have access to build the html in the first place, it might be easiest to add an extra attribute to the option element, like
<option init="WW" value="wordsworth">William Wordsworth</option>
<option init="PL" value="larkin">Phillip Larkin</opt
If you can't do this on the server-end, jQuery could easily insert an extra attribute to an option based on it's value. Assuming, of course, that you know in advance each of the values you'll have in there.
After getting the extra attribute into the option, it would just be a matter of checking those values on keyup of the search box.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With