简体   繁体   中英

button on-click prevents form submission

I have a snippet to prevent double clicks on links styled as buttons.

        $('.btn').on('click', function(e) {

            if( $(this).prop('disabled') == true) {
                $(this).attr("href","javascript:void(0);");
            } 

            $(this).prop('disabled',true);

        });

My problem is that this code seems to prevent any submit button from submitting a form. Is this an expected behavior from the above code?

It appears that disabling the button prevents the event from bubbling up the DOM and triggering the submit. There are several ways around this, but the easiest would probably be checking if it is a submit button on a form and handling it manually like so:

 $('.btn').on('click', function(e) { var trigger = $(this); if (trigger.prop('disabled') == true) { trigger.attr("href", "javascript:void(0);"); } trigger.prop('disabled', true); // disables form submit event bubbling if (trigger.is('[type="submit"], .submit')) { // check if submit button var form = trigger.closest("form, .form"); // find form if (form.length) { // if form exists form.submit(); // manually trigger form submit } } }); $("form").on("submit", function() { alert("submitting..."); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form style="border: 2px solid black; padding: 10px 0;"> Form: <input type="submit" class="btn" /> <button class="submit btn">.submit</button> </form> <br/> <button class="btn">Non-form button.btn</button> <input type="button" class="btn" value="non-form input.btn"> 

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