当我禁用提交按钮以防止双击时,为什么我的表单不发布?

发布于 2024-07-10 04:57:06 字数 1946 浏览 7 评论 0原文

与地球上所有其他 Web 开发人员一样,我也遇到了用户双击表单上的提交按钮的问题。 我的理解是,处理此问题的传统方法是在第一次单击后立即禁用按钮,但是当我这样做时,它不会发布

我确实对此做了一些研究,上帝知道有足够的信息,但其他问题例如 禁用表单上的按钮提交,禁用按钮似乎有效。 提交后禁用按钮的原始海报似乎和我有同样的问题,但是有没有提及他如何/是否解决了这个问题。

这里有一些关于如何重复它的代码(在 IE8 Beta2 中测试,但在 IE7 中也有同样的问题)

我的 aspx 代码

<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<script language="javascript" type="text/javascript">
    function btn_onClick()
    {
        var chk = document.getElementById("chk");
        if(chk.checked)
        {
            var btn = document.getElementById("btn");
            btn.disabled = true;
        }
    }
</script>
<body>
    <form id="form1" runat="server">
        <asp:Literal ID="lit" Text="--:--:--" runat="server" />
        <br />
        <asp:Button ID="btn" Text="Submit" runat="server" />
        <br />
        <input type="checkbox" id="chk" />Disable button on first click
    </form>
</body>
</html>

我的 cs 代码

using System;

public partial class _Default : System.Web.UI.Page 
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        btn.Click += new EventHandler(btn_Click);
        btn.OnClientClick = "btn_onClick();";
    }

    void btn_Click(object sender, EventArgs e)
    {
        lit.Text = DateTime.Now.ToString("HH:mm:ss");
    }
}

请注意,当您单击按钮时,会发生回发,并且时间会更新。 但是,当您选中该复选框时,下次单击该按钮时,该按钮将被禁用(如预期),但永远不会进行回发。

我到底错过了什么???

提前致谢。

Like every other web developer on the planet, I have an issue with users double clicking the submit button on my forms. My understanding is that the conventional way to handle this issue, is to disable the button immediately after the first click, however when I do this, it doesn't post.

I did do some research on this, god knows there's enough information, but other questions like Disable button on form submission, disabling the button appears to work. The original poster of Disable button after submit appears to have had the same problem as me, but there is no mention on how/if he resolved it.

Here's some code on how to repeat it (tested in IE8 Beta2, but had same problem in IE7)

My aspx code

<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<script language="javascript" type="text/javascript">
    function btn_onClick()
    {
        var chk = document.getElementById("chk");
        if(chk.checked)
        {
            var btn = document.getElementById("btn");
            btn.disabled = true;
        }
    }
</script>
<body>
    <form id="form1" runat="server">
        <asp:Literal ID="lit" Text="--:--:--" runat="server" />
        <br />
        <asp:Button ID="btn" Text="Submit" runat="server" />
        <br />
        <input type="checkbox" id="chk" />Disable button on first click
    </form>
</body>
</html>

My cs code

using System;

public partial class _Default : System.Web.UI.Page 
{
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        btn.Click += new EventHandler(btn_Click);
        btn.OnClientClick = "btn_onClick();";
    }

    void btn_Click(object sender, EventArgs e)
    {
        lit.Text = DateTime.Now.ToString("HH:mm:ss");
    }
}

Notice that when you click the button, a postback occurs, and the time is updated. But when you check the check box, the next time you click the button, the button is disabled (as expected), but never does the postback.

WHAT THE HECK AM I MISSING HERE???

Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

相思故 2024-07-17 04:57:06

我想你只是错过了这个标签:

UseSubmitBehavior="false"

试试这样:

<asp:Button ID="btnUpdate" runat="server" UseSubmitBehavior="false" OnClientClick="if(Page_ClientValidate()) { this.disabled = true; } else {return false;}" Text = "Update" CssClass="button" OnClick="btnUpdate_Click" ValidationGroup="vgNew"/>

说明

I think you're just missing this tag:

UseSubmitBehavior="false"

Try it like this:

<asp:Button ID="btnUpdate" runat="server" UseSubmitBehavior="false" OnClientClick="if(Page_ClientValidate()) { this.disabled = true; } else {return false;}" Text = "Update" CssClass="button" OnClick="btnUpdate_Click" ValidationGroup="vgNew"/>

Explanation

情话难免假 2024-07-17 04:57:06

UseSubmitBehavior="false" 将提交按钮转换为普通按钮 ()。 如果您不希望发生这种情况,可以隐藏提交按钮并立即在其位置插入禁用按钮。 因为这种情况发生得太快,所以用户看起来按钮被禁用了。 详细信息位于 Josh Stodola 的博客

代码示例(jQuery):

$("#<%= btnSubmit.ClientID %>").click(function()
{
  $(this)
    .hide()
    .after('<input type="button" value="Please Wait..." disabled="disabled" />');
});

UseSubmitBehavior="false" converts submit button to normal button (<input type="button">). If you don't want this to happen, you can hide submit button and immediately insert disabled button on its place. Because this happens so quickly it will look as button becoming disabled to user. Details are at the blog of Josh Stodola.

Code example (jQuery):

$("#<%= btnSubmit.ClientID %>").click(function()
{
  $(this)
    .hide()
    .after('<input type="button" value="Please Wait..." disabled="disabled" />');
});
轮廓§ 2024-07-17 04:57:06

Falling888 是对的,你的方法不适用于跨浏览器。 我使用

fallen888 is right, your approach doesn't work cross-browser. I use this little snippet to prevent double-click.

装纯掩盖桑 2024-07-17 04:57:06

“禁用”HTML 控件并不总是在所有主要浏览器中产生一致的行为。 因此,我尽量避免在客户端执行此操作,因为(使用 ASP.NET 模型)在这种情况下您需要跟踪客户端和服务器上的元素状态。

我要做的是将按钮的 className 切换为包含以下内容的 CSS 类,将按钮移出窗口的可见部分:

.hiddenButton
{
  position: absolute;
  top: -1000px;
  left: -1000px;
}

现在,用什么来代替按钮?

  1. 要么是看起来像禁用按钮的图像
  2. ,要么只是纯文本,上面写着“请稍候...”

,这可以以相同的方式完成,但相反。 从页面加载时隐藏的元素开始,然后在表单提交时切换到可见的 className。

"Disabling" HTML controls doesn't always produce consistent behavior in all major browsers. So I try to stay away from doing that on the client-side, because (working with the ASP.NET model) you need to keep track of element's state on client and server in that case.

What I'd do is move button off the visible part of the window by switching the button's className to a CSS class that contains the following:

.hiddenButton
{
  position: absolute;
  top: -1000px;
  left: -1000px;
}

Now, what to put in place of the button?

  1. Either an image that looks like a disabled button
  2. Or just plain text that says "Please wait..."

And this can be done the same way but in reverse. Start with the element being hidden at page load and then switch to a visible className on form submit.

七七 2024-07-17 04:57:06

我们使用以下 JQuery 脚本,在单击一个按钮时禁用所有按钮(输入类型=提交和按钮)。

我们只是将脚本包含在全局 JavaScript 文件中,因此在创建新按钮时无需记住任何内容。

$(document).ready(function() {
    $(":button,:submit").bind("click", function() {
        setTimeout(function() {
            $(":button,:submit").attr("disabled", "true");
        }, 0);
    });
});

通过检查 Page_ClientValidate() 可以轻松扩展此脚本。

We use the following JQuery script, to disable all buttons (input type=submit and button), when one button is clicked.

We just included the script in a global JavaScript file, so we don't have to do remember anything when creating new buttons.

$(document).ready(function() {
    $(":button,:submit").bind("click", function() {
        setTimeout(function() {
            $(":button,:submit").attr("disabled", "true");
        }, 0);
    });
});

This script could easily be extended with a check for Page_ClientValidate().

剪不断理还乱 2024-07-17 04:57:06
document.getElementById('form1').onsubmit = function() {
    document.getElementById('btn').disabled = true;
};
document.getElementById('form1').onsubmit = function() {
    document.getElementById('btn').disabled = true;
};
悲欢浪云 2024-07-17 04:57:06

这是执行此操作的正确且简单的方法:

它适用于所有浏览器(与上面接受的解决方案不同)。

在您的应用程序中创建一个辅助方法(例如在实用程序命名空间中):

    Public Shared Sub PreventMultipleClicks(ByRef button As System.Web.UI.WebControls.Button, ByRef page As System.Web.UI.Page)
        button.Attributes.Add("onclick", "this.disabled=true;" + page.ClientScript.GetPostBackEventReference(button, String.Empty).ToString)
    End Sub

现在,您可以从每个网页的隐藏代码中简单地调用:

    Utility.PreventMultipleClicks(button1, page)

其中,button1 是您想要防止多次单击的按钮。

其作用只是将单击处理程序设置为: this.disabled=true

,然后附加按钮自己的回发处理程序,因此我们得到:

onclick="this.disabled=true";__doPostBack('ID$ID',' ');"

这不会破坏页面的默认行为,并且可以按预期在所有浏览器中工作。

尽情享受!

This is the correct and simple way to do this:

It works in all browsers (unlike the accepted solution above).

Create a helper method in your application (say in a Utlity Namespace):

    Public Shared Sub PreventMultipleClicks(ByRef button As System.Web.UI.WebControls.Button, ByRef page As System.Web.UI.Page)
        button.Attributes.Add("onclick", "this.disabled=true;" + page.ClientScript.GetPostBackEventReference(button, String.Empty).ToString)
    End Sub

Now from the code behind of each of your web pages you can simply call:

    Utility.PreventMultipleClicks(button1, page)

where button1 is the the button you want to prevent multiple clicks.

What this does is simply sets the on click handler to: this.disabled=true

and then appends the buttons own post back handler, so we get:

onclick="this.disabled=true";__doPostBack('ID$ID','');"

This does not break the default behaviour of the page and works in all browsers as expected.

Enjoy!

日裸衫吸 2024-07-17 04:57:06

对于 JQUERY 用户

在使用 jQuery 事件侦听器时,尝试将 javascript 直接添加到 ASP.NET 按钮上的 onClick 事件时,您将遇到各种问题。

我发现禁用按钮并使回发正常工作的最佳方法是执行以下操作:

    $(buttonID).bind('click', function (e) {

        if (ValidateForm(e)) {

            //client side validation ok!
            //disable the button:
            $(buttonID).attr("disabled", true);

            //force a postback:
            try {
                __doPostBack($(buttonID).attr("name"), "");
                return true;
            } catch (err) {
                return true;
            }

        }
        //client side validation failed!
        return false;
    });

其中 ValidateForm 是您的自定义验证函数,如果您的表单验证客户端,它会返回 true 或 false。

buttonID 是按钮的 ID,例如“#button1”

FOR JQUERY USERS

You will get into all sorts of problems trying to add javascript directly to the onClick event on ASP.NET buttons when using jQuery event listeners.

I found the best way to disable buttons and get the postback to work was to do something like this:

    $(buttonID).bind('click', function (e) {

        if (ValidateForm(e)) {

            //client side validation ok!
            //disable the button:
            $(buttonID).attr("disabled", true);

            //force a postback:
            try {
                __doPostBack($(buttonID).attr("name"), "");
                return true;
            } catch (err) {
                return true;
            }

        }
        //client side validation failed!
        return false;
    });

Where ValidateForm is your custom validation function which returns true or false if your form validates client side.

And buttonID is the id of your button such as '#button1'

说谎友 2024-07-17 04:57:06

出于调试目的,如果对 if(chk.checked) 添加 else 子句会发生什么?

For debugging purposes, what happens if you put an else clause against the if(chk.checked)?

∞梦里开花 2024-07-17 04:57:06

确保您的 javascript 函数返回 true(或计算结果为布尔 true 的值),否则表单将无法提交。

function btn_click()
var chk = document.getElementById("chk");
    if(chk.checked)
    {
            var btn = document.getElementById("btn");
            btn.disabled = true;
            return true;   //this enables the controls action to propagate
    }
    else    return false;  //this prevents it from propagating
}

Make sure that your javascript function returns true (or a value that would evaluate to boolean true), otherwise the form won't get submitted.

function btn_click()
var chk = document.getElementById("chk");
    if(chk.checked)
    {
            var btn = document.getElementById("btn");
            btn.disabled = true;
            return true;   //this enables the controls action to propagate
    }
    else    return false;  //this prevents it from propagating
}
小镇女孩 2024-07-17 04:57:06

还可以尝试以下方法来防止双击“提交”按钮:

.buttonload {
    background-color: lightgrey; /* Grey background */
    border: none; /* Remove borders */
    color: black; /* Black text */
    padding: 12px 24px; /* Some padding */
    font-size: 16px; /* Set a font-size */
}

/* Add a right margin to each icon */
.fa {
    margin-left: -12px;
    margin-right: 8px;
}
<!DOCTYPE html>
<html>
<head>
    <!-- Add icon library -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <script type="text/javascript">
        $(function () {
            SubmitButton = $("#btn");
            SubmitButton.on("click", function () {
                result = ValidateRecords();
                if (result) {
                    $(this)
                        .hide()
                        .after('<button disabled class="buttonload"><i class= "fa fa-spinner fa-spin"></i>Processing Data...</button >');
                }
            });
        });

        function ValidateRecords() {
            var DateTime = document.getElementById('lit').value;
            if (!DateTime.trim()) {
                return false;
            }
            else {
                return true;
            }
        }
    </script>
</body>
</html>

说明(按上面代码出现的顺序):

  • CSS:处理用作替换按钮中图标标记一部分的微调器元素。
  • 如果您想使用图标类 fa-spinner,则必须在标题中添加图标库。
  • 在脚本标记中,调用 Validate 方法来检查在单击提交按钮之前是否填写了所有必需的表单元素。
  • 验证成功后,我隐藏提交按钮[ .hide()] 并替换为另一个按钮[.after()]。
  • 必须在新按钮上设置 DISABLED 属性,否则它将作为活动按钮使用。

注意:我使用 Button 替换了提交 Button。 但您可以根据您的要求使用输入文本或任何其他合适的元素

One can also try the following way to prevent double clicking of the "SUBMIT" Button:

.buttonload {
    background-color: lightgrey; /* Grey background */
    border: none; /* Remove borders */
    color: black; /* Black text */
    padding: 12px 24px; /* Some padding */
    font-size: 16px; /* Set a font-size */
}

/* Add a right margin to each icon */
.fa {
    margin-left: -12px;
    margin-right: 8px;
}
<!DOCTYPE html>
<html>
<head>
    <!-- Add icon library -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
    <script type="text/javascript">
        $(function () {
            SubmitButton = $("#btn");
            SubmitButton.on("click", function () {
                result = ValidateRecords();
                if (result) {
                    $(this)
                        .hide()
                        .after('<button disabled class="buttonload"><i class= "fa fa-spinner fa-spin"></i>Processing Data...</button >');
                }
            });
        });

        function ValidateRecords() {
            var DateTime = document.getElementById('lit').value;
            if (!DateTime.trim()) {
                return false;
            }
            else {
                return true;
            }
        }
    </script>
</body>
</html>

EXPLANATION(In Order of Code Appearance above):

  • CSS : Handles the spinner element used as part of the icon tag in the replaced button.
  • Adding the Icon Library in header is mandatory in case if you want to use the icon class fa-spinner.
  • In the script tag Validate method is called to check if all the mandatory form elements are filled prior clicking the submit button
  • Post the validation is successful, I am hiding the submit button[.hide()] and replacing with another button[.after()].
  • Setting the DISABLED property on the new button is mandatory or else it will work as an active button.

NOTE: I have used Button to replace the submit Button. But you can use input text or any other suitable element as per your requirements

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文