Jon
Jon

Reputation:

onkeydown event for html form not firing in IE 7 or FF 3

I am writing an asp.net application and have a form where a user must press a key to have a textbox become visible so that he/she can login. When the key is pressed, I want a label to disappear and a textbox to become visible. For some reason the 'onkeydown' event is not firing in FF or IE, but it works fine in Chrome. The application will be run on an AML terminal using the Links browser, but I am not able to test on that platform right now. Here is my code:

<form id="form1" runat="server" onkeydown="CheckKey(event.keyCode)" 
enableviewstate="True" submitdisabledcontrols="False" visible="True">

<script type="text/javascript">

    function SetVisibility() {
        var txtbx = document.getElementById("txtbx_login")
        txtbx.style.display = "none";
        var form = document.getElementById("form1")
    }

    function CheckKey(keycode) {
        if (keycode == 113) {
            var txtbx = document.getElementById("txtbx_login")
            txtbx.style.display = "";
            var lbl = document.getElementById("lbl_login")
            lbl.style.display = "none";
        }
    }

</script>

******other form elements******

</form>

The only way have been able to get the onkeydown event to work is if the textbox control is showing and has focus. Am I missing something? Thanks for the help!

Upvotes: 0

Views: 1566

Answers (1)

David Snabel-Caunt
David Snabel-Caunt

Reputation: 58361

I think the problem is that the onkeydown check is made on the form.

Try moving it to the body element, or better, use javascript to add the event handler to a window event:

function handleKeypress(e){

       var keycode = e.keyCode || e.charCode;

       if (keycode == 113) {
            var txtbx = document.getElementById("txtbx_login")
            txtbx.style.display = "";
            var lbl = document.getElementById("lbl_login")
            lbl.style.display = "none";
        }

    }
    window.onkeypress = handleKeypress;

In firefox you'll need to use event.charCode as well. I haven't tested the above in all browsers but it's a start.

Upvotes: 3

Related Questions