Alex
Alex

Reputation: 3968

Prevent validation on form.reset()

I have the following html form:

<body>
    <div>
        <form id="callBackForm" class="custom eight form" method="post" enctype="multipart/form-data" action="thank-you.php">
            <div class="callBackFormDivs"> 
                <div style="padding:0;" class="four mobile-one columns">
                    <label for="name" class="left inline">Name</label>
                </div>
                <div class="eight mobile-three columns">
                    <input class="left" id="name" name="name" required type="text" />
                </div>
            </div>
            <div class="callBackFormDivs">
                <div style="padding:0;" class="four mobile-one columns">
                    <label for="Age" class="left inline">Age</label>
                </div>
                <div class="eight mobile-three columns">
                    <input class="left" id="Age" name="Age" required type="text" />
                </div>
            </div>
            <div class="callBackFormDivs callBackFormButtonContainer">          
                <div>
                    <input type="submit" value="Submit" alt="Submit">
                    <button class="button" style="font-weight:normal; height:34px; float:right;" onClick="fnClearForm()">RESET</button>
                </div>                  
            </div>  
        </form>
    </div>

</body>

Note that the fields have a required attribute set on them. This attribute displays an error message to the user if they try to submit the form without entering any text.

There is a reset button on the page, which clears the fields, using the form.reset() function, as follows:

function fnClearForm()
{
    document.getElementById('callBackForm').reset();                    
}

The problem is, that when the form resets, it causes the validation to fire, and displays the error message to the user.

How do I prevent this?

I know I can write a custom validator, which will solve this, but I think it is best to find a way to make this validation work properly.

I did find some related question, but none of them solved the issue.

Upvotes: 2

Views: 131

Answers (1)

ptvty
ptvty

Reputation: 5664

Use the html attribute type to create a reset button.

<button type="reset" value="Reset">Reset</button>

http://www.w3schools.com/tags/att_button_type.asp

Fiddle: https://jsfiddle.net/2t2Lhnb8/

Upvotes: 3

Related Questions