I am trying to create an auto-suggest box. When a user starts typing in the #tagSelection input field, JQuery fetches suggestions from the database through Ajax and display these in the #suggestBox div that is displayed right under the #tagSelection field.
Now I want to enable the user to use the arrow down key to select one of the suggestions. I have started building this by handling the keydown() event and assigning a class to the first entry during this event. The problem I am facing is that the class is removed again when I let go of the arrow down key. I need it to stay assigned when I let go of the key. Is that possible?
The HTML
<div class="form-entry">
<input id="tagSelection" name="tags" type="text" value="" size="40">
<div id="suggestBox" style="">
<a href="#" id="1">design</a>
<a href="#" id="3">debit card</a>
<a href="#" id="4">deer</a>
<a href="#" id="addTag">Add word</a>
<div id="selectedTags"></div>
</div>
The JQuery
(function() {
$('#tagSelection').keydown(downArrowKeyHandler);
})();
function downArrowKeyHandler(event) {
if (event.keyCode == 40) {
if ($('#suggestBox').length > 0) {
if ($('[tagSelected = 1]').length == 0) {
// the tagSelected class gives the entry a colored background
$('#suggestBox').children().filter(':first').addClass('tagSelected');
}
}
}
}
I found the exact same problem here:
How to make a permanent change to an element after using jQuery's .keydown()?
It seems I indeed had some other JQuery code that was interfering with my event handler. Whenever someone releases a key when in the #tagSelection field a JQuery method fires that retrieves the suggestions from the db. The already present keyup() event was interfering with my new keydown() event.
(function() {
$('#tagSelection').keyup(tagboxTypingHandler)
})();
function tagboxTypingHandler(event) {
if (event.keyCode != 40) {
var substring = $('#tagSelection').val();
if (substring.length > 1) {
$.get("http://localhost:8080/tag/search/" + substring, returnedTagsHandler);
}
}
}
I just added the event.keyCode != 40 condition and now the class remains on the suggestion and it works :-)