jQuery ajax禁用提交按钮,直到表单完成

时间:2019-01-26 07:48:05

标签: jquery

下面有显示和处理表单的代码。脚本工作正常,但现在我需要禁用提交按钮,直到表单上的字段完成为止。哪个是正确的方法?

我的脚本

$( function() {
$(".input").val("");
var dialog1, form,
dialog1 = $( "#dialog-form1" ).dialog({
dialogClass: 'ui-dialog-content1',
autoOpen: false,
maxHeight: 500,
height: 500,
width: 800,
modal: true,
buttons: [
{
 text: "Reset",
 click: function() {
   $('#Form1').trigger("reset");
   $("#imageviewdiv").hide();
   $("#pcicon").hide();
   $('#Preview4').html("");
   $('#previewtext').html("");
   $('#imageis').hide();
   $('#image_position_portrait').hide();
 }},
 {
 text: "Cancel",
 click: function() {
   $('#Form1').trigger("reset");
   $("#imageviewdiv").hide();
   $("#pcicon").hide();
   $('#Preview4').hide();
   $(this).dialog("close");
}},
{
text: "Submit",
click: function() {
var form = document.getElementById("Form1");
   var fd = new FormData(form );
   $.ajax({
     url: "insert_new_promotion.php",
     data: fd,
     cache: false,
     processData: false,
     contentType: false,
     type: 'POST',
     success: function (dataofconfirm) {
      window.location.reload();
    }
  });
  $(this).dialog("close");
 }}
]
});
$( "#new-record" ).button().on( "click", function() {
  dialog1.dialog( "open" );
});
});

非常感谢您的宝贵时间。

2 个答案:

答案 0 :(得分:2)

您可以在Ajax调用之前或在beforeSend回调上禁用该按钮。请参阅callback function queues的文档。 Event.target是允许您获得单击按钮的工具。

$("#dialog-form1").dialog({
  dialogClass: 'ui-dialog-content1',
  autoOpen: false,
  maxHeight: 500,
  height: 500,
  width: 800,
  modal: true,
  buttons: [
    {
      // Other buttons
    }, 
    {
      text: "Submit",
      click: function (e) {
        var button = e.target;
        var form = document.getElementById("Form1");
        var fd = new FormData(form );

        // Either disable it here or on `beforeSend` callback.
        button.disabled = true;

        $.ajax({
          url: "insert_new_promotion.php",
          data: fd,
          cache: false,
          processData: false,
          contentType: false,
          //beforeSend: function() {
          //  button.disabled = true;
          //},
          type: 'POST',
          success: function (dataofconfirm) {
            // You may not need to re-enable the button since you are reloading the page anyway
            button.disabled = false;

            window.location.reload();
          }
        });

        $(this).dialog("close");
      }
    }
  ]
})

答案 1 :(得分:0)

您可以添加事件处理程序,只需为所有文本字段提供一个通用类,然后检查是否所有这些文本字段都已填充

$('.input-fields').on('change',function(){
    var disable = false
   $('.input-fields').each(function(){
      if($(this).val() == ''){
         disable = true
      }

    }

    $('#button-id').prop('disabled',disable)

})

第二种方法

data-toggle="validator" novalidate="true"标记中添加<form>,并将required添加到必填字段,它将自动禁用提交按钮

让我知道是否需要更多帮助

相关问题