Search code examples
jqueryeventsfirefoxlivekeycode

jQuery - even.keyCode not being recognized correctly in firefox?


the code below works properly in IE and Chrome (latest versions)

$('#searchBox').keyup(function () {
    var searchTxt = $(this).val();

    // if item contains searchTxt,
    if ($('.item:contains("' + searchTxt + '")')) {
        // hide the items that do NOT contain searchTxt
        $('.item').not(':contains(' + searchTxt + ')').hide();
    };

    // capture backspace
    if (event.keyCode == 8) {
        // show item that contains searchTxt
        $('.item:contains(' + searchTxt + ')').show();
    };

    // if search box is empty, 
    if ($('#searchBox').val() == "") {
        // show all items
        $('.item').show();
    };
});

the code above performs a "case sensitive live search" and fails to execute the chunk of code that captures the backspace key in firefox:

// capture backspace
if (event.keyCode == 8) {
    // show item that contains searchTxt
    $('.item:contains(' + searchTxt + ')').show();
};

Solution

  • Put event argument in:

    $('#searchBox').keyup(function (event) { .. });

    and instead of keyCode user event.which.

    Read more about event.which