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

Q891 How can I change all occurences of one character to another character within all the text and textareas in a form?

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

Try the following:

<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;
}

function replaceFormFields(what,text,by) {
    for (var i=0; i<what.elements.length;i++) {
        if (what.elements[i].name.indexOf('text') != -1)
            what.elements[i].value = replace(what.elements[i].value,text,by);
    }
}
//--></script>

<script language="JavaScript1.1"><!--
function replaceFormFields(what,text,by) {
    for (var i=0; i<what.elements.length;i++) {
        if (what.elements[i].type == 'text' || what.elements[i].type == 'textarea')
            what.elements[i].value = replace(what.elements[i].value,text,by);
    }
}
//--></script>

<form>
<input name="text1" type="text" value="x xx xxx xx x">
<br><textarea name="text2">x xx xxx xx x</textarea>
<p><input type="button" onClick="replaceFormFields(this.form,'x','y')">
</form>

©2018 Martin Webb