Javascript - clear forms

ameoba

Supreme [H]ardness
Joined
Jan 9, 2001
Messages
6,412
I'm trying to make a button to clear the forms on a page. I have this as the onclick

Code:
for (f in document.forms) {
    for (e in document.elements) {
        if (e.type == 'text'){
            e.value = '.';
        } else if (e.type == 'select') {
            e.selectedIndex = 1;
        }
    }
}

...but it does nothing. Am I missing something important?
 
its been a long time since i've used it,

but have you tried the form button
<FORM name='formname'>
<INPUT TYPE='reset'>
</FORM>


you can also in javascript do

document.formname.reset()

is it just the selected forms or the drop downs that aren't resetting?
 
The problem with reset is that it only resets the inputs back to their default values.

What's going on here is that a user is inputting some info, if it doesn't validate, the screen comes back saying 'error - please try again' with their last input still in the form. I'd like to give them the option of clearing the form and starting over.
 
ameoba said:
I'm trying to make a button to clear the forms on a page. I have this as the onclick

...but it does nothing. Am I missing something important?
Yeah, f and e are not what you think they are. :p

Code:
for (f=0;f<document.forms.length;f++) {
    for (e=0;e<document.forms[f].elements.length;e++) {
        var x = document.forms[f].elements[e];
        if (x.type == 'text'){
            x.value = '.';
        } else if (x.type == 'select') {
            x.selectedIndex = 1;
        }
    }
}
 
I didn't fix your other minor problems. Hints:

do you really want to select the second item as default?

are you clearing select one or multiple?

:p
 
It's a select one. I ended up just testing for the existance of x.selectedIndex and went with 0. The 1 ended up in there due to frustration & wondering if my problem was caused by 1-based indexing instead of 0.

So, what's the difference between the two? If document.forms is an array (as I was lead to believe by docs I've seen), why does a foreach loop fail when indexing into the array works? If it's not an array, what is it?
 
You really shouldnt be referencing your form via document.forms. Use getElementById() instead:

http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-A6C9094
Code:
<script type="text/javascript">
 userInformation = document.getElementById('UserInformation');

 for(i = 0; i < userInformation.getElementsByTagName('input').length; i++) {
 }
 for(i = 0; i < userInformation.getElementsByTagName('select').length; i++) {
 }
</script>

<form id="UserInformation">
 <input />
 <select />
</form>

--KK
 
Back
Top