【问题标题】:How to disable submit button AFTER browser has validated fields with 'required' attribute?如何在浏览器验证具有“必需”属性的字段后禁用提交按钮?
【发布时间】:2015-07-19 12:38:57
【问题描述】:

我们正在使用以下 jQuery 禁用提交按钮,以防止重复提交(服务器速度慢!)。

jQuery(document).ready(function($){

    /*SENDE BTN INAKTIV STELLEN*/
    $("input[type=submit]").click(function() {
        $(this).css({'opacity':'0.5','cursor':'wait'}).attr('disabled','disabled');
    });

});

但是,在浏览器验证了 HTML 表单中所有具有“必需”属性的字段后,我们如何触发脚本?

【问题讨论】:

  • 您需要一个事件监听器,在浏览器验证字段后创建禁用按钮功能。
  • 验证是如何调用的?巴一些 onSubmit 处理程序?如果是,请出示此代码

标签: jquery html validation required


【解决方案1】:
EDIT: I found a much more elegant way to do this. Please accept this answer if it works for you.

 jQuery(document).ready(function($){

/*SENDE BTN INAKTIV STELLEN*/
    $("input[type=submit]").click(function() {

        var myform = $('#theform');

        //checks if the form is valid
        if(myform[0].checkValidity())
        {
             $(this).css({'opacity':'0.5','cursor':'wait'}).attr('disabled','disabled');
        }
    });

});


//this is slightly awkward but it works

jQuery(document).ready(function($){

/*SENDE BTN INAKTIV STELLEN*/
$("input[type=submit]").click(function() {
    var flag = true;

    $('[required]').each(function(){
        if(!$(this).val()) 
           flag = false;
    });

    if(flag){
       $(this).css({'opacity':'0.5','cursor':'wait'}).attr('disabled','disabled');
    }
    else
       return false;
});

});

【讨论】:

  • 谢谢阿尔弗雷多。稍微更改了代码以使其适用于所有表单: if($('form[0]').checkValidity())
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-14
相关资源
最近更新 更多