禁用后点击提交按钮,几秒钟后再次启用(Disable the submit button after

2019-06-25 06:47发布

提交表单时,我使用jQuery $。员额。 我想对于像5秒禁用按钮被点击,避免多次提交表单后。

这里就是我现在做:

$('#btn').click(function(){
    $.post(base_url + 'folder/controller/function',$('#formID').serialize(),function(data){
        $('#message').slideDown().html('<span>'+data+'</span>');
    });
});

我用淡入淡出和前,但仍当我测试了一下按钮,迅速地它不工作。 我应该怎么做才能达到我想要的东西会发生什么?

Answer 1:

你可以做你想要的东西是这样的:

var fewSeconds = 5;
$('#btn').click(function(){
    // Ajax request
    var btn = $(this);
    btn.prop('disabled', true);
    setTimeout(function(){
        btn.prop('disabled', false);
    }, fewSeconds*1000);
});

或者可以使用jQuery的.complete()正被所述AJAX之后执行方法接收响应:

$('#btn').click(function(){
    var btn = $(this);
    $.post(/*...*/).complete(function(){
        btn.prop('disabled', false);
    });
    btn.prop('disabled', true);

});

编辑: 这是一个示例 3秒的服务器端响应延迟



Answer 2:

只要把这个在您的JS页面的提交按钮上

<script type="text/javascript">
  $(document).ready(function(){
    $("input[type='submit']").attr("disabled", false);
    $("form").submit(function(){
      $("input[type='submit']").attr("disabled", true).val("Please wait...");
      return true;
    })
  })
</script>

源代码



Answer 3:

看一看在.success功能在这里您需要什么。

所以你要做的就是在单击禁用按钮

$('#btn').click(function(){
    $('#btn').attr('disabled', true);
    $.post(base_url + 'folder/controller/function', $('#formID').serialize(), function(data) {
        // code on completion here
        })
        .success(function() { 
           $('#btn').attr('disabled', false);
        })
    });
});

这种方式是,如果你的请求花费超过5秒,作为回报,会发生什么好?



Answer 4:

        $('#btn').live('click', function () {
            $(this).prop('disabled', true).delay(800).prop('disabled', false);
        });

//要么

 $('#btn').live('click', function () {
            var obj = $(this);
            obj.prop('disabled', true);
            $.post(base_url + 'folder/controller/function', $('#formID').serialize(), function (data) {
                $('#message').slideDown().html('<span>' + data + '</span>');
                obj.prop('disabled', false);
            });
        });


文章来源: Disable the submit button after clicking and enable it back again after a few seconds