Directional Arrows in Object

Asked

Viewed 107 times

0

I did a city search using Javascript.

There is a text field in which the user type the city name. And as he’s typing the letters, the respective cities that start with that letter appear in a ul > li below the field for the user to click.

You can use the down and up arrow keys to navigate between cities and when the focus is on the li tighten 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 he only navigates between the first and the last.

  • 1

    You can mount html to make it easier to understand ?

  • It has several autocomplete plugins, you want to do "in the nail", that’s it?

  • I want to do nail, don’t need a plugin for this...

  • 1

    So ta. I was going to recommend <datalist> but the support is limited. If you write your own autocomplete, put as answer.

  • My autocomplete is already ready, but it’s not the problem. The problem is my arrow navigation.

1 answer

1


See if this solves:

$("#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: https://jsfiddle.net/7fzqps3o/1/

  • Your code only works on the first and last element of the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.