PDA

View Full Version : fromCharCode. Quick question.



cursed
01-23-2008, 04:07 AM
Why doesn't this work? I think i'm overlooking something stupid:confused:
function unicodeToText(event)
{
var asciitext = "";
asciitext = String.fromCharCode(event.keyCode);
makeRequest('http://test.com/index.html?receive=' + asciitext);
}


assume that the ajax process is after this, and that index.html could recieve the stuff that javascript is giving to it

Thanks in advance!

jscheuer1
01-23-2008, 07:48 AM
it should work in FF. It should perhaps work in IE, it depends on how it is called. I would think it would be called from a onkeydown event. If you assign it via an element's onkeydown attribute like this:


<body onkeydown="unicodeToText(event);">

for example, it would work in all modern browsers, provided there was body enough to provide a target for the event:


<!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">
function unicodeToText(event)
{
var asciitext = "";
asciitext = String.fromCharCode(event.keyCode);
alert('http://test.com/index.html?receive=' + asciitext);
}
</script>
</head>
<body onkeydown="unicodeToText(event);">
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
<p>Hi</p>
</body>
</html>

I've made some body by filling it with p elements. I changed the output to an alert, since I didn't have your Ajax code.

But if you call it like so, via direct assignment:


document.onkeydown=unicodeToText;

IE will not see the event, so the function would need to be amended to at least something like:


function unicodeToText(event)
{
var asciitext = "", ev=event? event : window.event;
asciitext = String.fromCharCode(ev.keyCode);
alert('http://test.com/index.html?receive=' + asciitext);
}

I would write it like so:


function unicodeToText(e){
var ev=e? e : window.event? window.event : null,
n=ev&&ev.keyCode? ev.keyCode : ev&&ev.which? ev.which : null;
if(n)
alert('http://test.com/index.html?receive=' + String.fromCharCode(n));
}

That way it wouldn't do anything if not supported, not even raise an error. And it could be called either way, as an element's event attribute, or via direct assignment.

cursed
01-24-2008, 12:17 AM
The examples you gave work perfectly:).

Thanks for taking time to explain how I could optimize it and fixing my errors.

Regards,

Edward