Click to See Complete Forum and Search --> : Type on Page


Dysan
01-17-2008, 11:23 AM
Using JavaScript, how do I enable the user to type directly onto the screen, and store each character entered, as a string inside a hidden form field?

Dysan
01-17-2008, 12:03 PM
Is it possible to enter text directly on the page using JavaScript?

JPnyc
01-17-2008, 01:16 PM
Yes, it is possible.

Dysan
01-17-2008, 01:30 PM
How? Can you give me some example code?

JPnyc
01-17-2008, 02:44 PM
Sorry, it's not a short simple script to write, but I can tell you that you needsomething like this code to find which key was pressed

Which key has been pressed?
This one is relatively easy. First get the code of the key (a = 65) from the keyCode property.

When you’ve read out the key code, send it through the method String.fromCharCode() to obtain the actual key value, if necessary.

function doSomething(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert('Character was ' + character);
}

Which I found on http://www.quirksmode.org/js/events_properties.html

and you have to build a string into a global variable using +=. The variable must be global (declared outside of a function) because otherwise it would reset every time the function was called. Then you have to call the function onkeyup event.

As for updating the page, the function will contain a statement like:

document.getElementById('elId').innerHTML

Or you could use the DOM methods, which will achieve the same results with more code

JPnyc
01-17-2008, 02:49 PM
it would simplify the script a great deal if you could put a text area into your page for them to type into. Then you don't have to worry about grabbing which key was pressed. The browser would do that, and you could just set the value of some element to the value of the text area.