jQuery 验证成功后启用禁用按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21953694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 01:46:55  来源:igfitidea点击:

Enabling disabled button after successful jQuery validation

jqueryjquery-validatetwitter-bootstrap-3

提问by LJT

I have the following code where I have 2 email input fields which I need to validate they are the same which is working successfully using jQuery validate equalTo.

我有以下代码,其中有 2 个电子邮件输入字段,我需要验证它们是否相同,使用 jQuery validate equalTo 可以成功运行。

<div class="control-group">
 <label class="control-label" for="inputEmail"><strong>Email Address</strong></label>
   <div class="controls">
    <input type="email" name="inputEmail" placeholder="[email protected]" id="inputEmail" required>
   </div>
    <label class="control-label" for="inputEmailConfirm"><strong>Confirm Email Address</strong></label>
     <div class="controls">
    <input type="email" name="inputEmailConfirm" placeholder="[email protected]" id="inputEmailConfirm" required>
    </div>
    </div>
  <button type="submit" id="emailSubmit" disabled="disabled" class="btn btn-danger" data-toggle="tooltip" data-placement="bottom" title="Click me to buy">Credit Card Checkout &raquo; </button>

Upon successful validation I wish to enable the button, but can't seem to figure out how to do this.

成功验证后,我希望启用该按钮,但似乎无法弄清楚如何执行此操作。

 $('#ccSelectForm').validate({
    rules: {
      inputEmail: {
        required: true,
        email: true
      },
      inputEmailConfirm: {
        required: true,
        email: true,
        equalTo: '#inputEmail'
      },
    }
  });

Ideally as bonus I'd like to set the form controls to utilise the validation states in Bootstrap3, detailed here - http://getbootstrap.com/css/#forms-control-validation

理想情况下,作为奖励,我想设置表单控件以利用 Bootstrap3 中的验证状态,详情见此处 - http://getbootstrap.com/css/#forms-control-validation

Fiddle is here http://jsfiddle.net/4wU5m/

小提琴在这里http://jsfiddle.net/4wU5m/

回答by Sparky

There is no jQuery Validate plugin callback option/function that fires when all fields are valid without first clicking the submit button.

没有 jQuery Validate 插件回调选项/函数在所有字段都有效时触发,而无需先单击提交按钮。

You'll need to create an external keyup blurevent handler that checks your form for validity and enables/disables the button accordingly; every time a key is pressed or you leave a field.

您需要创建一个外部keyup blur事件处理程序来检查表单的有效性并相应地启用/禁用按钮;每次按下一个键或您离开一个字段时。

DEMO: http://jsfiddle.net/p628Y/1/

演示:http: //jsfiddle.net/p628Y/1/

$(document).ready(function () {

    $('#ccSelectForm').validate({
        rules: {
            inputEmail: {
                required: true,
                email: true
            },
            inputEmailConfirm: {
                // required: true,  // <-- redundant
                // email: true,     // <-- redundant
                equalTo: '#inputEmail'
            }  // <-- removed trailing comma
        }
    });

    $('#ccSelectForm input').on('keyup blur', function () { // fires on every keyup & blur
        if ($('#ccSelectForm').valid()) {                   // checks form for validity
            $('button.btn').prop('disabled', false);        // enables button
        } else {
            $('button.btn').prop('disabled', 'disabled');   // disables button
        }
    });

});    

Since the jQuery Validate plugin disables the browser's HTML5 validation dynamically, I removed the requiredattribute from your markup and changed type="email"into type="text". (You already have these validation rules specified in the plugin.)

由于 jQuery Validate 插件动态禁用浏览器的 HTML5 验证,我required从您的标记中删除了该属性并将其更改type="email"type="text". (您已经在插件中指定了这些验证规则。)

<input type="text" name="inputEmail" placeholder="[email protected]" id="inputEmail" />
<input type="text" name="inputEmailConfirm" placeholder="[email protected]" id="inputEmailConfirm" />

You also don't need to specify all the rules twice when using the equalTorule as the second field must already always match the first.

使用规则时,您也不需要两次指定所有equalTo规则,因为第二个字段必须始终与第一个字段匹配。



EDIT:

编辑:

In the above scenario, your page is totally dependent upon JavaScript. In other words, without JavaScript, the button is always disabled.

在上述场景中,您的页面完全依赖于 JavaScript。换句话说,如果没有 JavaScript,按钮将始终处于禁用状态。

If you have server-side validation in place and want your page to be independent of JavaScript, you'll need to remove the disabled="disabled"from your button markup and add it to your JavaScript just inside the DOM ready event handler.

如果您有服务器端验证并希望您的页面独立于 JavaScript,您需要disabled="disabled"从按钮标记中删除,并将其添加到您的 JavaScript 中的 DOM 就绪事件处理程序中。

$('button.btn').prop('disabled', 'disabled');

In this scenario, without JavaScript, you'll still have a working button, and with JavaScript, the button is disabled programatically on page load.

在这种情况下,如果没有 JavaScript,您仍然会有一个可用的按钮,而使用 JavaScript,该按钮在页面加载时以编程方式禁用。

回答by user3709159

A more elegant and fast solution is to simply override the default on-click and on-keyup events adding the code you need as follows instead of adding another listen event

一个更优雅和快速的解决方案是简单地覆盖默认的点击和按键事件,添加您需要的代码,如下所示,而不是添加另一个监听事件

$("#form").validate({
    submitHandler: function(form) {
        form.submit();
    },
    onkeyup: function( element, event ) {
        if ( event.which === 9 && this.elementValue(element) === "" ) {
            return;
        } else if ( element.name in this.submitted || element === this.lastElement ) {
            this.element(element);
        }

        this.checkForm();

        if (this.valid()) { // checks form for validity
            $('a.submit').attr('class', 'submit btn btn-success');        // enables button
        } else {
            $('a.submit').attr('class', 'submit btn btn-danger disabled');   // disables button
        }
    },
    onclick: function( element ) {
        // click on selects, radiobuttons and checkboxes
        if ( element.name in this.submitted ) {
            this.element(element);

        // or option elements, check parent select in that case
        } else if ( element.parentNode.name in this.submitted ) {
            this.element(element.parentNode);
        }

        this.checkForm();

        if (this.valid()) { // checks form for validity
            $('a.submit').attr('class', 'submit btn btn-success');        // enables button
        } else {
            $('a.submit').attr('class', 'submit btn btn-danger disabled');   // disables button
        }
    }
})

With the following css code for the submit trigger - initially disabled (bootstrap 3 classes):

使用以下提交触发器的 css 代码 - 最初禁用(引导程序 3 类):

<a onclick="if(!$(this).hasClass('disabled')) { $('#form').submit(); }" class="submit btn btn-danger disabled">button_save</a>

This can very easy be used with jquery plug-in areYouSureto only enable the submit when actual changes are made:

这可以很容易地与 jquery 插件areYouSure一起使用,以仅在进行实际更改时启用提交:

if (this.valid() && $('#form').hasClass('dirty')) { // checks form for validity

initializing the plug-in using silent:

使用silent初始化插件:

$('#form').areYouSure( {'silent':true} );