Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

onkeypress enter key

Status
Not open for further replies.

SideShowBob1972

Programmer
Jan 12, 2009
6
GB
I have some code which checks for the enter key being pressed and then executes some code.

function enterPressed(evn) {
if (window.event && window.event.keyCode == 13) {
Some code
} else if (evn && evn.keyCode == 13) {
Some Code
}
}
document.onkeypress = enterPressed;

It works on every browser except Safari on Mac.

Any suggestions?
 
Does Safari/Mac ever run either branch of the code? Have you tried putting alerts in to see if it does? Or, if it does, what values are given?

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
Safari/Mac does not run either branch of the code.

I have checked and when you press enter it does return keycode 13
 
OK - you have code (which we can't see) that gives you the value 13, but your existing code that tests for the value 13 fails.

So, how about using the code that gives you the value 13 in your tests?

Dan



Coedit Limited - Delivering standards compliant, accessible web solutions

Dan's Page [blue]@[/blue] Code Couch:
Code Couch Tech Snippets & Info:
 
I used the following code to echo the code of each key.

<script language="JavaScript">
document.onkeydown = checkKeycode
function checkKeycode(e) {
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
alert("keycode: " + keycode);
}
</script>

How do I adapt it to detect a specific key being pressed?
 
Here is how I handle the enter key:

In HTML, I have:
Code:
<input type="text" id="someInput" onkeypress="handleEnter(this, event)" />

In my JavaScript file, I have:
Code:
function handleEnter(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("Enter was pressed on " + inField.id);
    }
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top