pistevw
pistevw

Reputation: 432

Iterate through array and jump to next item on keypress

I have an array with letters that I want to iterate with up and down keys and then choose a letter with enter and jump to next with enter but I have no idea how to achieve that. So far I've got this:

var i = 0;

var letters = ['a','b','c','d','e']

$(document).ready(function() {
  $(document).keypress(function(e) {

    e.preventDefault();

    var keyCode = e.which;
        arrow = {up: 38, down: 40, enter: 13};

    switch(e.keyCode)
    {
        case arrow.up:
            alert('up');
        break;

        case arrow.down:
            alert('down');
        break;

        case arrow.enter:
            $('#box').html(letters[++i % letters.length]);
        break;
    }
});
});

So my first question is: This goes through the array on enter key, but I can't change the key value. If I want to make the down key iterate the array, nothing happens, what do I do wrong? And the second: how can I do to jump to a new letter on keypress?

Update:

Okey, now I'm closer to what I wanted:

case arrow.up:
            $('#letterbox').html(letters[--i % letters.length]);
        break;

        case arrow.down:
            $('#box').html(letters[++i % letters.length]);
        break;

        case arrow.enter:
            $('#box2').html(letters[++i % letters.length]);
        break;

The up and down key iterates through the array and the enter prints a new letter to the div '#box2' but it continues to iterate the first box. How can I make the array iterate from the current box?

Upvotes: 2

Views: 1685

Answers (2)

Taplar
Taplar

Reputation: 24965

Something like this maybe? http://jsfiddle.net/hdyjLLr9/3/

<input type="text" id="displayCurrentSelection" />
<input type="text" id="enterSelection" />

JS

var i = 0;
var letters = ['a', 'b', 'c', 'd', 'e'];
var $currentSelection;
var $enterSelection;

$(document).ready(function () {
    var arrow = {
                up: 38,
                down: 40,
                enter: 13
            };

    $enterSelection = $('#enterSelection');
    $currentSelection = $('#displayCurrentSelection');
    $currentSelection.val(letters[i]);

    $(document).keypress(function (e) {
        e.preventDefault();

        var keyCode = e.keyCode || e.which;

        switch (keyCode) {
            case arrow.up:
                i = (++i) % letters.length;
                break;
            case arrow.down:
                if (i > 0) i--;
                else i = letters.length - 1;
                break;
            case arrow.enter:
                $enterSelection.val(letters[i]);
                i = (++i) % letters.length;
                break;
        }
        $currentSelection.val(letters[i]);
    });
});

Upvotes: 1

ImreNagy
ImreNagy

Reputation: 511

I don't know exactly why but keypress does not track the arrow keys. Use keydown instead.

Upvotes: 2

Related Questions