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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With