I've got some jQuery code to focus a <select> dropdown based on user input, as per a previous question. Here it is:
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
$("#userlist").keypress(function (e) {
initials += String.fromCharCode(e.which).toUpperCase();
// when the relevant initials are typed, select that item
$(this).find("option").filter(function () {
return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
}).first().attr("selected", true);
$('#book_results').html(loading_img); // Show 'loading' gif
// Then use get_books function to update some HTML on the page with relevant info
get_books($(this).find("option").filter(function () {
return $(this).attr("title").toUpperCase().indexOf(initials) === 0;
}).first().val(), null, null);
if (timer) {
clearTimeout(timer);
timer = null;
}
timer = setTimeout(function () {
timer = null;
initials = "";
}, 2000); // Max 2 second pause allowed between key presses
return false;
});
It's very promising, but I'm finding that when the user types e.g. 'WW', "William Shakespeare" is selected first, and all the HTML on the page updates for him, and only after a couple of seconds does the dropdown 'catch up' and update for "William Wordsworth".
I'm certain that this is my fault for not handling the flow of events correctly, but could anyone suggest a fix? N.B. I can't guarantee that every item will have two initials.
Thanks for helping out a JavaScript novice!