mardi 5 mai 2015

Chaining jquery keydown event

I am trying to create a drop down like functionality where a div is shown once somebody starts typing in the input box. I am able to attach mouse click event on the individual elements to select them. But I am not able to select them via pressing enter.

HTML

<input type="text" class="input" name="example" id="example" placeholder="example..." autocomplete="off" list="examplelist" />

<div class="autofill">
    <ul class="autocomplete">
        <li class="autocomplete-list">John Doe (San Jose, CA)</li>
        <li class="autocomplete-list">Jane Doe (San Francisco, CA)</li>
        <li class="autocomplete-list">John Jane (San Carlos, CA)</li>
    </ul>
</div>

JQuery

$(document).ready(function () {
var $listItems = $('li.autocomplete-list'),
    $div = $('div.autofill'),
    $input = $('#example');

$div.hide();

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

    $div.show();

    if (key != 40 && key != 38) 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');

    // When I press enter after selecting the li element
    // Does not work :(
    $current.on('keypress keydown keyup', 'li', function (event) {
        if (event.keyCode == 13) {
            var value = $(this).text().split('(')[0].trim();
            $input.val(value) ;
            $div.hide();
        }
    });
});


// If somebody clicks on the li item
$('li.autocomplete-list').on('click', function (e) {
    var value = $(this).text().split('(')[0].trim();
    $input.val(value);
    $div.hide();
});

// change color on hover
$('li.autocomplete-list').hover(
    function(){ $(this).addClass('hover') },
    function(){ $(this).removeClass('hover') }
);

// When I press enter after selecting the li element
// Does not work :( 

$('li.autocomplete-list').on('keypress keydown keyup', 'li', function (event) {
    if (event.keyCode == 13) {
        var value = $(this).text().split('(')[0].trim();
        $input.val(value) ;
        $div.hide();
    }
  });
});

How can I select a particular li element and then take its value when press enter? Here is the JSFiddle

Aucun commentaire:

Enregistrer un commentaire