There is a code:

if (e.which == 40) { $(".list-ul").next(".list-li").focus(); element.val($(".list-li").val()); } 

Implies going through the list

 <ul class = "list-ul"> <li class = "list-li"></li> .... <li class = "list-li"></li> </ul> 

but something is not working. How correct?

  • 2
    does not work, because you call next() on the list and want to iterate the children, but it returns the neighboring node. Those. adjacent to ul , not a child - teran

1 answer 1

You have confusion, because you need to use both ul and li focused, and everything should be clear:

 $(window).keydown(function(e) { if (e.which == 40) { //проверяем выбрано ли что-либо if($(".list-li:focus").length!==0){ //если выбрано, выбираем следующий элемент $(".list-li:focus").next(".list-li").focus(); }else{ //если не выбрано, выбираем первый элемент $(".list-ul .list-li").eq(0).focus(); } $('#element').val($(".list-li:focus").text()) } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="list-ul"> <li class="list-li" tabindex="1">1</li> <li class="list-li" tabindex="2">2</li> <li class="list-li" tabindex="3">3</li> </ul> <input id=element>