Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q690 How do I capture a character that is typed into a textarea and change it to another character?

You are here: irt.org | FAQ | JavaScript | Form | 6 | Q690 [ previous next ]

Try:

<HTML>

<HEAD>
<SCRIPT LANGUAGE="JavaScript"><!--
function replace(string,text,by) {
    // Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}
//--></SCRIPT>
</HEAD>
<BODY>

<FORM NAME="myForm">
<TEXTAREA COLS="20" ROWS="10" onChange="this.value=replace(this.value,'x','y')"></TEXTAREA>
</FORM>

</BODY>
</HTML>

If you attempt to change the value whilst the user is typing using onKeyUp="this.value=replace(this.value,'x','y')" then you'll find that the text caret insertion point jumps to the front of the text field - causing confusion.

©2018 Martin Webb