简体   繁体   中英

multiple form submits after fixing html5 validation errors

I have a form that I do not want to submit until the HTML5 validation has worked its magic, displayed errors, etc. I have the Save button bound to a click function. If the user clicks the Save button, but errors are found (via HTML validation), then fixes the errors, then clicks Save button again, the form is submitted twice. If the cycle of error showing and fixing is repeated multiple times, the form is submitted multiple times.

The following code (also found at in this fiddle ) demonstrates this. Click on "Save" without filling in the firstname/lastname inputs. Then fill in the inputs and click "Save" again. You'll see by the alert messages that messages #1 thru #3 are repeated twice. Weird that the validation function isn't called at all with the first click (empty name boxes) and then its called twice when the entries are valid.

Note: the code works just fine if the boxes are filled in before "Save" is clicked the first time.

There must be something I'm not understanding about HTML5 form validation and the submit event, but I have spent hours googling this and trying different things to no avail. What is triggering the repetitive submit event? Help appreciated!

 $('body').on('click','#Save', function (ev) { //ev.preventDefault(); alert('duh - click captured'); $('#client_form').submit(function (e) { alert('1 - submit fired'); e.preventDefault(); e.stopPropagation(); handle_client_form(e); }); }); function handle_client_form(e) { if (manualValidate(e)) { alert('3a - good to go; process form inputs'); } else { alert('3b - invalid form'); } } function manualValidate(e) { if (e.target.checkValidity()) { alert('2 - validate OK!'); e.stopPropagation(); return true; } else { e.stopPropagation(); return false; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="client_form"> <input name="FirstName" placeholder="first name" required/> <input name="LastName" placeholder="last name" required /> <button id="Save">Save</button> </form> 

You are registering multiple click event listeners. A call to .off() will fix this.

$('body').on('click','#Save', function (ev) {
    //ev.preventDefault();

    alert('duh - click captured');

    $('#client_form').submit(function (e) {

        alert('1 - submit fired');

        e.preventDefault();
        e.stopPropagation();

        handle_client_form(e);
    });

$('body').off('click');
});

I have updated your fiddle here: http://jsfiddle.net/frqgtsdo/

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