Directional Arrows in Object

0

I did a city search using Javascript.

There is a text field in which the user types the city name. And while he is typing the letters, the respective cities starting with that letter appear in a ul > li under the field for the user to click.

You can use the up and down arrow keys to navigate between cities and when the focus is on li press enter to select the city?

JS

if(str != ''){
    box_div.show();
    box_ul.html('');
    $.each(data, function(i, val){
        box_ul.append("<li id='"+val.id+"'>"+val.cidade+", "+val.estado+"</li>");
    });
}
var linhas = $('div.resultados-cidades > ul > li');
var cont   = linhas.length;

if(40 == event.keyCode )
    active = active >= (cont - 1) ? 0 : active + 1;
else if(38 == event.keyCode )
    active = ( active <= 0 ) ? cont - 1 : active - 1;

var a = linhas.removeClass('hover').eq(active).addClass('hover');

In this function it only navigates between the first and last.

    
asked by anonymous 11.03.2016 / 18:44

1 answer

1

See if this resolves:

$("#inputCidade").keydown(function(e) {
    if (e.keyCode == 13) { // enter
        if ($(".cidades").is(":visible")) {
            opcaoEscohida();
        } else {
            $(".cidades").show();
        }
        menuOpen = !menuOpen;
    }
    if (e.keyCode == 38) { // pra cima
        var selected = $(".selected");
        $(".cidades li").removeClass("selected");
        if (selected.prev().length == 0) {
            selected.siblings().last().addClass("selected");
        } else {
            selected.prev().addClass("selected");
        }
    }
    if (e.keyCode == 40) { // pra baixo
        var selected = $(".selected");
        $(".cidades li").removeClass("selected");
        if (selected.next().length == 0) {
            selected.siblings().first().addClass("selected");
        } else {
            selected.next().addClass("selected");
        }
    }
});
function opcaoEscohida() {
    $("#inputCidade").val($(".selected a").text());
    $(".cidades").hide();
}

Fiddle: link

    
11.03.2016 / 19:08