Search code examples
htmlvalidationjsperror-handlingstruts

How do you clear a form after struts validation error


I have a form (JSP) and I'm using Struts to validate the text fields. An example would be to display an error if the user enters numbers inside of the First name text box since it will only accept letters. The message stays on the screen along with the numbers. When you right click and do a view source code, you can see the numbers there as if they're hard coded.

I have a html:reset button but it won't clear the numbers out of the text box. If you click on the text box and clear the numbers manually after the validation error, then click the Reset button, it puts the numbers right back in. I have tried many different pieces of code using the DOCUMENTS class with a function inside of a script tag. Here is one of many pieces of code I've tried:

 <input type="button" value="Clear Form" onclick="clearForm()"/> 

 <script type="text/JavaScript">
     function clearForm() {
     document.getElementById("FirstName").value=" ";  }
 </script>

I have also tried the get elements by class name and also by tag name methods but nothing is working.

My first name text box id is FirstName. The jsp is using HTML with Struts. Any help will be appreciated and if anyone who is willing needs more information I will provide it. Thank you all.


Solution

  • This is my answer: function clear_form_elements(ele) {

    tags = ele.getElementsByTagName('input');
    for(i = 0; i < tags.length; i++) {
        switch(tags[i].type) {
            case 'password':
            case 'text':
                tags[i].value = '';
                break;
            case 'checkbox':
            case 'radio':
                tags[i].checked = false;
                break;
        }
    }
    
    tags = ele.getElementsByTagName('select');
    for(i = 0; i < tags.length; i++) {
        if(tags[i].type == 'select-one') {
            tags[i].selectedIndex = 0;
        }
        else {
            for(j = 0; j < tags[i].options.length; j++) {
                tags[i].options[j].selected = false;
            }
        }
    }
    
    tags = ele.getElementsByTagName('textarea');
    for(i = 0; i < tags.length; i++) {
        tags[i].value = '';
    }
    

    }

    Then I just call this function with the button and it clears everything out. Thanks for your help though.