9

I have following HTML structure ('ul li' are rendered as drop-down/select)

<input id="input_city" type="text" />

<div class="suggestions">
 <ul>
  <li value="0" name="New York">New York</li>
  <li value="1" name="London">London</li>
  <li value="2" name="Paris">Paris</li>
  <li value="3" name="Sydney">Sydney</li>
 </ul>
</div>

Need JavaScript/jQuery code to capture down arrow key press event (on input) which will select first 'li' element

Consecutive down key select next 'li' elements; and up key select previous 'li' elements.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
I-M-JM
  • 15,732
  • 26
  • 77
  • 103

2 Answers2

25

Since your question is a little too vague, it's not exactly clear what you're trying to accomplish.

If you're trying to highlight the li elements, use this:

var $listItems = $('li');

$('input').keydown(function(e) {
    var key = e.keyCode;
    var $selected = $listItems.filter('.selected');
    var $current;

    if (![38, 40].includes(key)) return;

    $listItems.removeClass('selected');

    if (key == 40) { // Down key
        if (!$selected.length || $selected.is(':last-child')) {
            $current = $listItems.eq(0);
        } else {
            $current = $selected.next();
        }
    } else if (key == 38) { // Up key
        if (!$selected.length || $selected.is(':first-child')) {
            $current = $listItems.last();
        } else {
            $current = $selected.prev();
        }
    }

    $current.addClass('selected');
});​

Here's the fiddle: http://jsfiddle.net/GSKpT/


If you're just trying to set the value of your input field, change the last line to this:

$(this).val($current.addClass('selected').text());

Here's the fiddle: http://jsfiddle.net/GSKpT/1/

Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
0

You can use MousetrapJS for this. Here an example how you could implement the down key. First add the class selected to the first list item.

Mousetrap.bind('down', function() {
    var next = $(".suggestions  li.selected").removeClass("selected").next();
    if (next.length) {
       next.addClass("selected");
    } else {
       $(".suggestions li").first().addClass("selected");
    }
});
Split Your Infinity
  • 4,159
  • 1
  • 21
  • 19