0

Been knocking up a simple suggestion box on an input field.. all working as it should so far except for two issues I can't seem to resolve:

1) when onkeypress event fires, the value of the input box is not correct - it misses off the last character! So for e.g. if you enter 3 chars only first two get carried through. so sometimes suggestions aren't totally accurate!

2) I need to watch out for users pressing the arrow down key, and then set focus to the first list item in the suggestion box! Can't seem to get this working though!

Have included code for you to look at! Any suggestions welcomed.. However I don't really want to use a plugin seeing as I have this 95% done already..

Here is the jsfiddle link! http://jsfiddle.net/beardedSi/kr4Cq/

Note - I just noticed that in the fiddle verison as I have put dummy array in the code it is no longer matching suggestions - but this doesn't matter, it works fine in my working code!

    work = true;
function finish() {
    work = true;
}

var autoComp = $('.autoComp');
var skillInput = $('.new-skills input');


$('.new-skills input').keypress(function (e) {
    var param = $(skillInput).val();
    if (param.length > 0) {
        $.getJSON('/recruiter/home/GetAutocompleteSkills?term=' + param, function (data) {
            $(autoComp).slideDown().empty();
            var items = [];
            $.each(data, function (key, val) {
                items.push('<li><a href="">' + val + '</a></li>');
            });
            $(autoComp).append(items.join(''));
            $('.base-wrapper a').not('.button').click(function (e) {
                work = false;
                e.preventDefault();
                $(skillInput).val($(this).text());
                $(autoComp).empty().slideUp(500, finish);
            });

        });
    }

});

$(skillInput).keydown(function (e) {
    if (e.keyCode == 40) {
        console.log("down");
        $('.autoComp li:first:child').focus();
    }
});
$('.new-skills input').blur(function () {
    if (work == true)
        $(autoComp).slideUp();
});
Jon Stevens
  • 21
  • 1
  • 7
  • 1
    for point 1, try using keyup rather than keypress. http://api.jquery.com/keyup/. It is probably missing the last character as the event is being dispatched on keydown and the character has not actually been set. – r8n5n Sep 26 '12 at 10:05
  • 1
    great, have a read of this for point 2, http://stackoverflow.com/questions/2847879/jquery-set-focus-on-dynamic-content. – r8n5n Sep 26 '12 at 10:18
  • thanks! Got it working with .trigger('focus') – Jon Stevens Sep 26 '12 at 10:48

0 Answers0