jQuery validation works with input type=“submit”, but not html button element. Why?

二次信任 提交于 2020-01-04 04:23:05

问题


Using ASP.NET, why is it that the bassistance.de jQuery validation plugin prevents form submission when using input type="submit" elements, and not html button elements?

The validation fires when using an html button (type="submit") tag, but the form is still submitted.

Is there a way to make the jQuery validation plugin work with html button elements?

A quick example:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <script type="text/javascript">
            $(document).ready(function () {
                $("#form1").validate({
                    rules: {
                        txtFirstName: {
                            required: true
                        }
                    },
                    messages: {
                        txtFirstName: {
                            required: "* First Name required<br/>"
                        }
                    }
                });
            });
        </script>
    </head>

    <body>
        <form id="form1" runat="server">
            <input id="txtFirstName" name="txtFirstName" type="text" />
            <input id="btnSubmit1" type="submit" runat="server" value="Submit" /> <!-- WORKS! -->
            <button it="btnSubmit2" type="submit" runat="server">Submit</button> <!-- DOESN'T WORK -->
        </form>
    </body>
</html>

回答1:


It appears to be designed that way:

// when a submitHandler is used, capture the submitting button
if (validator.settings.submitHandler) {
  inputsAndButtons.filter(":submit").click(function () {
    validator.submitButton = this;
  });
}

Unfortunately that seems to be baked in, with no other option. The documentation on :select seems to shed some more light on this:

The :submit selector typically applies to button or input elements. Note that some browsers treat element as type="default" implicitly while others (such as Internet Explorer) do not.

One solution would be to bind your button to a function that invokes the validation. In the example below we see this being done with an anchor:

$("#myform").validate();
$("a.check").click(function() {
  $("#myform").valid();
});


来源:https://stackoverflow.com/questions/10666890/jquery-validation-works-with-input-type-submit-but-not-html-button-element-w

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