Victor
Victor

Reputation: 555

How to Fire Keypress event in IE for a button event

I have develop asp.net application in that I have search option for the clients. When I enter the client name in textbox then I press the Enter key from keyboard it is working fine in Firefox and Chrome but didn't fire in IE8 here I have post my code what I did for KeyEvent fire:

<script type="text/javascript">
    function KeyPress() {
        if (event.keyCode == 13) { //if they pressed enter key then..
            document.formname.LoginButton.focus();
        }
    }
</script>

How can I resolve this to fire the Keypress event in IE? Please help me...

Upvotes: 0

Views: 1584

Answers (2)

GoRoS
GoRoS

Reputation: 5375

Try this solution.

HTML:

<input type="text" id="txtNombre" onkeypress="manejadorEnter(this, event)" />

Javascript (include it in the code-behind or in HTML):

function manejadorEnter(inField, e) {
    var charCode;

    if(e && e.which){
        charCode = e.which;
    }else if(window.event){
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13) {
        alert("La tecla enter ha sido pulsada en " + inField.id);
    }
}

Upvotes: 1

GoRoS
GoRoS

Reputation: 5375

I have just tried my code shown above and it works fine for all browsers. Just try the following HTML file (obviously enable JavaScript in your browser):

<html>
<head>
<title>Test enter button keypress</title>
<script language="javascript" type="text/javascript">
function handlerEnter(inField, e) {
    var charCode;

    if(e && e.which){
        charCode = e.which;
    }else if(window.event){
        e = window.event;
        charCode = e.keyCode;
    }

    if(charCode == 13) {
        alert("You pressed Enter button at " + inField.id);
    }
}
</script>
</head>
<body>
<input type="text" id="txtNombre" onkeypress="handlerEnter(this, event)" />
</body>
</html>

For more complicated JavaScript scripts, I strongly suggest to take a look at JQuery.

Good luck!

Upvotes: 0

Related Questions