PDA

View Full Version : Help with Event Object & Onkeypress



Jus S
06-30-2008, 11:54 AM
Hello all, I'm trying to create a script that has a dual purpose. The first is to create an input field that converts the value into upper case upon losing focus. The second shows the keys pressed using the following: event object for detecting the key, document.onkeypress to capture the event, and String.fromCharCode(Keycode) to convert the keycode obtained from the event back to a character. I accomplished the first goal but the second goal eludes me. Below is what I've been working with. What am I doing wrong?
Thanks,
Jus

<html>
<head>
<script type="text/javascript">
var x = function () {
document.getElementById('field').value = document.getElementById('field').value.toUpperCase();
}
otherCase = x;
otherCase();
</script>
<script type="text/javascript">
function DisplayKey (e) {
//which key has been pressed?
var keycode;
if (!e) var e = window.event;
else if (e.keyCode) keycode=e.keyCode;
else if (e.which) keycode=e.which;
character=String.fromCharCode(keycode)
// find the object for the destination paragraph
k = document.getElementById('keys')
document.onkeypress=DisplayKey(event);
// add the character to the paragraph
k.innerHTML += character;
}
</script>
</head>
<body>
<form>
<table align="center">
<tr><td><b>Input Field:</b></td>
<td><input name="fld" type="text" id="field" onblur="otherCase();"></td>
</tr>
</table>
</form>
<form type="text" id="keys" onkeypress="DisplayKey(event)"></form>
<h1>Display pressed keys</h1>
</body>
</html>

jscheuer1
06-30-2008, 12:32 PM
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
var otherCase = function () {
document.getElementById('field').value = document.getElementById('field').value.toUpperCase();
}
window.onload = otherCase;

function DisplayKey (e) {
e = e? e : window.event;
//which key has been pressed?
var keycode = e.keyCode? e.keyCode : e.which? e.which : null;
if(keycode)
document.getElementById('keys').firstChild.nodeValue += String.fromCharCode(keycode);
}
document.onkeypress=DisplayKey;
</script>

</head>
<body>
<form action="javascript:void();" onsubmit="return false;">
<table align="center">
<tr><td><b>Input Field:</b></td>
<td><input name="fld" type="text" id="field" onblur="otherCase();"></td>
</tr>
</table>
</form>
<h1>Display pressed keys:</h1>
<div id="keys">
&nbsp;
</div>

</body>
</html>

You might want to add the event onkeypress to the (or another) input field instead of to the document, example:


<input name="fld" type="text" id="field" onblur="otherCase();" onkeypress="DisplayKey(event);">

Also, although the code tested fine, I've often heard that onkeydown is preferred for this sort of thing.