简体   繁体   中英

Disabling a submit button when clicking on it , will prevent the form from being submitted on Google Chrome

I have added the following script to my layout view, inside my asp.net mvc :-

$(document).ready(function () {
    $('.btn.btn-primary').click(function () {
        $(this).prop("disabled", true);
        if (!$('form').valid()) {
            $(this).prop("disabled", false);
            return false;
        }
    });
    $('form').change(function () {
        $('.btn.btn-primary').prop("disabled", false);
    });

The aim of my script is to disable the submit buttons , and re-enable them if the model is not valid or if the user change a form value. The above script will work well on IE & Firefox, but on Chrome I am unable to submit the form , as when the user clicks on the submit button , the button will be disable but the form will not be submitted. Any idea how I can solve this issue on Chrome?

Instead disabling button in button's click event - disable it in form's submit event (you can check form for validity there as well).

This way it will work universally in all browsers.

<form action="http://www.microsoft.com">
  <input class="btn-primary" type="submit" value="submit"/>
</form>


$('form').submit(function() {
  $('input.btn-primary').prop("disabled", "disabled");
})

I just had the same issue that the Google Chrome was not fireing my submit event when the button got disabled via jQuery .

Background info: I have a form with a button that shall be disabled whenever clicked. So the PHP submit code is not called multiple times. That submit is running on a Drupal Backend, in my case as a custom submit_hook . But for sure working in any other CMS. But that's not the issue. The real issue is that the Javascript code is disabling the button and Google Chrome thinks that the button is totally dead and not just disabled. So it does not fire any code anymore.

But that issue is pretty easy to fix.

So this code is working on Firefox / IE :

(function($) {
Drupal.behaviors.somebehaviour = {
    attach: function(context, settings) {
        $('#edit-submit').click(function (e) {
            $('#edit-submit').val('Is saved...');
            $('#edit-submit').prop('disabled', 'disabled');
        });
    }
};
})(jQuery);

and getting it running on Chrome as well, you need to add the line:

$(this).parents('form').submit();

so for this example it would finally be:

(function($) {
Drupal.behaviors.somebehaviour = {
    attach: function(context, settings) {
        $('#edit-submit').click(function (e) {
            $('#edit-submit').val('Is saved...');
            $('#edit-submit').prop('disabled', 'disabled');
            $(this).parents('form').submit();
        });
    }
};
})(jQuery);

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