简体   繁体   中英

Select li element with arrow keys (up and down) using Javascript (jQuery)

I got this problem...I have an input which works as searcher and when I write something it show an ul with the list of matches and it works, the <ul> and <li> items are generated with PHP via AJAX

This is my input

<input type="text" class="form-control" id="searchProduct" placeholder="Search..." />

在此处输入图片说明

This is the <ul>

<ul id="list">
    <li id="match1" class="itemList"></li>
    <li id="match2" class="itemList"></li>
    <li id="match3" class="itemList"></li>
</ul>

After the list is generated the focus is still on the input and it's ok but I would like to use the arrow keys (up and down) to select one of the items

And I'm trying with code that I see in another answer but it is not working for me, I know that I'm doing something wrong but i can't figure out what the problem is... this is the javascript code

var li = $('#list > li');
var liSelected;
$(window).on('keydown', function(e){
    if(e.which === 40){
        if(liSelected){
            liSelected.removeClass('background');
            next = liSelected.next();
            if(next.length > 0){
                liSelected = next.addClass('background');

            }else{
                liSelected = li.eq(0).addClass('background');
            }
        }else{
            liSelected = li.eq(0).addClass('background');
        }
    }else if(e.which === 38){
        if(liSelected){
            liSelected.removeClass('background');
            next = liSelected.prev();
            if(next.length > 0){
                liSelected = next.addClass('background');

            }else{

                liSelected = li.last().addClass('background');
            }
        }else{

            liSelected = li.last().addClass('background');
        }
    }
});

NEW INFO:

$('#searchProduct').keyup(function() {

var search = $(this).val();

if (search != '') {

    $.ajax({

        type: 'post',
        cache: false,
        url: '../includes/procedures/autocomplete.php',
        data: { search: search },

        success: function(datos) {

            $('#coincidenciasBusqueda').show();
            $('#coincidenciasBusqueda').html(datos);
        }
    });
}

});

I give your window's function a arguments to catch the value, every time when you press arrow key. and print it out. just like below.

 var li = $('#list > li'); var liSelected; $(window).on('keydown', function(e){ var selected; if(e.which === 40){ if(liSelected){ liSelected.removeClass('background'); next = liSelected.next(); if(next.length > 0){ liSelected = next.addClass('background'); selected = next.text(); }else{ liSelected = li.eq(0).addClass('background'); selected = li.eq(0).text(); } }else{ liSelected = li.eq(0).addClass('background'); selected = li.eq(0).text(); } }else if(e.which === 38){ if(liSelected){ liSelected.removeClass('background'); next = liSelected.prev(); if(next.length > 0){ liSelected = next.addClass('background'); selected = next.text(); }else{ liSelected = li.last().addClass('background'); selected = li.last().text() } }else{ liSelected = li.last().addClass('background'); selected = li.last().text() } } console.log(selected) }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <link rel="stylesheet" href=""> <style> .background{ background: hsla(0, 100%, 0%, 0.4); } </style> </head> <body> <input type="text" class="form-control" id="searchProduct" placeholder="Search..." /> <ul id="list"> <li id="match1" class="itemList">1</li> <li id="match2" class="itemList">2</li> <li id="match3" class="itemList">3</li> </ul> </body> </html> 

If you want to set to your input box, just give selected's value to it or you also can replace selected to $('searchProduct') .

I think you're looking for something like:

$(function(){

var li = $('#list li'), n = -1, ll = li.length-1;
$('#searchProduct').keypress(function(e){
  var x = e.which;
  li.removeClass('background');
  if(x === 40 || x === 39 || x === 38 || x === 37){
    if(x === 40 || x === 39){
      n++;
      if(n > ll)n = 0;
    }
    else if(x === 38 || x === 37){
      n--;
      if(n < 0)n = ll;
    }
    var ci = li.get(n);
    ci.addClass('background'); $(this).val(ci.text());
  }
});

});

you can use the build-in datalist to achieve arrow key select

<input list="browsers" name="browser">
<datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
</datalist>
<input type="submit">

You could use jquery autocomplete along with ajax and PHP via JSON. So now you can use the arrow keys to select. You can also do some CSS to customize the drop-down's look and feel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM