Search code examples
javascriptjqueryinputgoogle-suggest

How can I use the arrow keys in Jquery


I'm trying to mimic the Google suggestions list with this:

function el(tid) {
    return document.getElementById(tid);
}

function addScript(u) {
    var head = document.getElementsByTagName('head')[0],
        sc2 = document.createElement('script');
    sc2.src = u;
    head.appendChild(sc2);
    setTimeout(function () {
        head.removeChild(sc2);
        sc2 = null;
    }, 600);
} //end addScript()

function suggest(data) {
    var sel = el("test");
    sel.innerHTML = '';
    for (x = 0; x < data[1].length; x++) {
        sel.innerHTML += '<li class="uli" >' + data[1][x][0] + '</li>';
    }
}


el("inp").onkeyup = function () {
    addScript("http://www.google.nl/complete/search?callback=suggest&q=" + this.value);
};

The problem is that I want to be able to come down in the suggestions list using the arrow keys, and secondary I want to show the 'current' suggestion value inside the input field. So I tried something like this using Jquery:

$("#inp").live("keydown", function (e) {


    var curr = $('#test').find('.current');
    if (e.keyCode == 40) {
        if (curr.length) {
            $(curr).attr('class', 'uli');
            curr = $(curr).next();
        }
        if (curr.length) {
            curr.attr('class', 'uli current');
        } else {
            $('#center li:first-child').attr('class', 'uli current');

        }
    }
    if (e.keyCode == 38) {
        if (curr.length) {
            $(curr).attr('class', 'uli');
            curr = $(curr).prev();
        }
        if (curr.length) {
            curr.attr('class', 'uli current');
        } else {
            $('#center li:last-child').attr('class', 'uli current');
        }
    }







    $("#inp").live("keydown", function (e) {
        var search_terms = $('li.current').text();

        if (e.keyCode == 40) {
            $('#inp').val(search_terms);
        }
        if (e.keyCode == 38) {
            $('#inp').val(search_terms);

        }

It doesn't work because (I think..) the 'current' suggestion is immediately being requested by the previous code. I have put everything over here: JS Bin


Solution

  • Why recreate the wheel?

    jQuery UI Autocomplete

    Or look at other plugins

    The problem with your code is you need to cancel out the arrow keypresses when you call to get the values.

    el("inp").onkeyup = function () {
        //if not the arrow keys, fetch the list
        if( ... ){
            addScript("http://www.google.nl/complete/search?callback=suggest&q=" + this.value);
        }
    }
    

    Also what is with el("inp") when you are using jQuery? I expected to see $("foo").keyup( function(){} );