简体   繁体   中英

Select div with up/down arrows

I have text input, and when I focusing on it - first '.option' of '#number_list' become '.selected'. I want to create a feature - when Up or Down key on keybord pressed than next or prev element of 'number_list' granding 'selected' class and current element loosing this class.

<input type="text" name="number" id="number" maxlength="30" />

<div id="number_list">
  <div class='option selected'>aaa</div>
  <div class='option'>bbb</div>
  <div class='option'>ccc</div>
</div>

http://jsfiddle.net/YNyEr/

I was trying to create array of '.option' elements and get current element by index, but I don't find any way to do this. So how can it be done? Also I'm using jQuery 1.5.1.

How about this quick-and-dirty implementation: http://jsfiddle.net/zerkms/YNyEr/2/

var $input = $('#some_number'),
    current_index = $('.selected').index(),
    $number_list = $('#number_list'),
    $options = $number_list.find('.option'),
    items_total = $options.length;

$input.val(current_index);

$input.bind('keyup', function(e) {
    if (e.keyCode == 40) {
        if (current_index + 1 < items_total) {
            current_index++;
            change_selection();
        }
    } else if (e.keyCode == 38) {
        if (current_index > 0) {
            current_index--;
            change_selection();
        }
    }
});

function change_selection()
{
    $options.removeClass('selected');
    $options.eq(current_index).addClass('selected');
    $input.val(current_index);
}​

I think you should have a look at the javascript events onkeyup and onkeydown. If you play with the selection by id it should be quite easy,

For instance

<div onkeydown='document.getElementById("nextid").className += "selected";this.className -= "selected";' class='option'>bbb</div>

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