简体   繁体   中英

How to prevent form submission while using HTML5 client-side form validation in Opera 11?

How to prevent form submission while using HTML5 client-side form validation in Opera 11?

Here is a sample test page:

 <section> <h2>Test</h2> <form> <input type="text" name="test" id="test" required/> <input type="submit" value="Test" /> </form> </section> 

Validation works in Opera 11, but when the button is clicked after entering a value, the browser submits the form.

I want the browser to stay on the webpage always, which is good for client-side-only scripts, on the local hard drive, where there is no server, for example.

When I add return false; or try to prevent the form from submitting, the validation no longer works.

Opera 11.10 Build 2092

EDIT:

Thanks to robertc's solution, I got it working. Here is the test page without jQuery.

  (function() { "use strict"; window.addEventListener("load", function() { document.getElementById("testForm").addEventListener("submit", function(event) { event.target.checkValidity(); event.preventDefault(); // Prevent form submission and contact with server event.stopPropagation(); }, false); }, false); }()); 
 <section> <h2>Test</h2> <form id="testForm"> <input type="text" name="test" id="test" required/> <input type="submit" value="Test" /> </form> </section> 

OK, try this . The form is basically as before:

<section>
    <h2>Test</h2>
    <form id="form">
        <input type="text" name="test" id="test" required/>
        <input type="submit" value="Test"/>
    </form>
</section>

Then bind the submit event to a function which calls the checkValidity() method:

function manualValidate(ev) {
    ev.target.checkValidity();
    return false;
}
$("#form").bind("submit", manualValidate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM