Search code examples
javascriptjqueryfocuskeypress

jQuery Focus() or keypress() not working in IE and Chrome


I have the code blow for tabbing through 2 fields and it has no effect in IE and Chrome, it seems it runs nothing (for example I get nothing when I put alert) and in Firefox it runs with some bug (it jumps twice there) where do you think the problem is, I'm developing in by ASP.Net and jQuery version 1.3.2

$(document).ready(function () {
    $("#TextBox1").keypress(function (e) {
        var kCode = e.keyCode || e.charCode; 
        if (kCode == 9) {
            $("#TextBox2").focus();
        }
    });
});

Solution

  • I think the main problem is that you're using the keypress event, which should only be fired when a character is added to the input, not when any key (like TAB) is pressed.

    To handle other key presses you will need to use keydown. However, testing that in your fiddle seems to still not work. To make it work (in Chrome at least), I had to prevent the default action:

    $(document).ready(function () {
        $("#TextBox1").keydown(function (e) {
            e.preventDefault();
            var kCode = e.keyCode || e.charCode; 
            console.log(kCode);
             if (kCode == 9) {
                $("#TextBox2").focus();
            }
        });
    });
    

    Here's an update fiddle. However, if I've understood your question correctly, all you're trying to do is change the focused element when the tab key is pressed... if that's right, why not just use the tabindex attribute instead?