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

Q940 How can I write my own reset function to reset form fields to their default values?

You are here: irt.org | FAQ | JavaScript | Form | 9 | Q940 [ previous next ]

There already is a form reset() method that you can use, but if you want your own then the following (almost) works:

<script language="JavaScript"><!--
function resetDefaultValues(what) {
    for (var i=0, j=what.elements.length; i<j; i++) {
        myName = what.elements[i].name;
        if (myName.indexOf('checkbox') > -1 || myName.indexOf('radio') > -1)
            what.elements[i].checked = what.elements[i].defaultChecked;
        if (myName.indexOf('hidden') > -1 || myName.indexOf('password') > -1 || myName.indexOf('text') > -1)
            what.elements[i].value = what.elements[i].defaultValue;
        if (myName.indexOf('select') > -1)
            for (var k=0, l=what.elements[i].options.length; k<l; k++)
                what.elements[i].options[k].selected = what.elements[i].options[k].defaultSelected;
    }
}
//--></script>

<script language="JavaScript1.1"><!--
function resetDefaultValues(what) {
    for (var i=0, j=what.elements.length; i<j; i++) {
        myType = what.elements[i].type;
        if (myType == 'checkbox' || myType == 'radio')
            what.elements[i].checked = what.elements[i].defaultChecked;
        if (myType == 'hidden' || myType == 'password' || myType == 'text' || myType == 'textarea')
            what.elements[i].value = what.elements[i].defaultValue;
        if (myType == 'select-one' || myType == 'select-multiple')
            for (var k=0, l=what.elements[i].options.length; k<l; k++)
                what.elements[i].options[k].selected = what.elements[i].options[k].defaultSelected;
    }
}
//--></script>

<form name="myForm">
<br><input name="checkbox1" type="checkbox"><input name="checkbox2" type="checkbox" checked>
<br><input name="hidden" type="hidden" value="hidden value">
<br><input name="password" type="password" value="password value">
<br><input name="radio" type="radio" checked><input name="radio" type="radio">
<br><input name="text" type="text" value="text value">
<br><textarea name="textarea">textarea value</textarea>
<br><select name="select1">
<option>0
<option>1
<option selected>2
<option>3
</select>
<br><select name="select2" multipe size="2">
<option>0
<option>1
<option selected>2
<option>3
</select>
<p><input type="button" value="Reset Default Values" onClick="resetDefaultValues(this.form)">
</form>

It cannot set the value of the password field as a password fields value is read-only.

It can set the value of the hidden field, but hidden fields do not have defaultValues support in JavaScript.

©2018 Martin Webb