How can I disable all buttons and links on my page, but still let the postback occur?

六眼飞鱼酱① 提交于 2019-12-11 16:41:46

问题


I'm trying to prevent the user from clicking on more than one postback-causing element on the page. In other words, if they click the 'continue' submit button, they shouldn't be able to cause another postback before the original request comes back.

I've had a go with two versions of jQuery code. Neither does exactly what I want:

This version will disable all the postback elements, but in doing so, it stops the clicked element from firing. For the record, I don't think the .removeAttr('onclick') is really required, but leaving it out doesn't seem to change the behaviour.

$(function() {
    $('a, :button, :submit').click(function() {
        var elements = $('a, :button, :submit');
        elements.attr('disabled', 'disabled').removeAttr('onclick');
    });
});

This version disables all other postback elements, but it lets me reuse the same element that was clicked - I don't want to be able to hit the same button twice.

$(function() {
    $('a, :button, :submit').click(function() {
        var otherelements = $('a:not(#' + $(this).attr('id') + '), :button:not(#' + $(this).attr('id') + '), :submit:not(#' + $(this).attr('id') + ')');
        elements.attr('disabled', 'disabled').removeAttr('onclick');
    });
});

How can I prevent this behaviour?


回答1:


I just tested your first approach without JQuery, and it worked fine, i.e. disabling the submit button didn't prevent the form submission.

<form method="get">
  <input type="text" name="textfield" value="a" />
  <input type="submit" onclick="this.disabled=true">
</form>

Maybe you want to double check is there is anything else, e.g. JQuery, going on?




回答2:


Maybe you could put a flag or something that it could remember what button it was clicked and if that flag exist, you can remove the onclick event on that postback-causing element. But I think this cannot be done in client side scripting alone, since once the page is submitted, all client side elements and scripts are refreshed.




回答3:


Perhaps instead of making this a click function make it onmouseup so it fires after the click event has occured.




回答4:


Here's a final version that worked - just overriding the form submit event rather than looking at any individual elements.

var submitted = false;
$(function() {
    $('form').bind('submit', function() {
        if (!submitted) {
            submitted = true;
            return true;
        } else {
            return false;
        }
    });
});

Thanks all for your suggestions.



来源:https://stackoverflow.com/questions/3412336/how-can-i-disable-all-buttons-and-links-on-my-page-but-still-let-the-postback-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!