如何在JQuery对话框按钮中触发表单提交或传递表单对象?

时间:2019-03-14 13:46:42

标签: javascript jquery jquery-ui-dialog

我有带有表单的JQuery对话框。对话框中有两个按钮SubmitCancel。当用户单击Submit时,我要提交表单数据。这是我的代码示例:

$(document).on('click', '#show_btn', showDialog);

function showDialog() {
  var myHtml = "<form id='myfrm' method='post'><div><input type='checkbox' name='status1' id='status1'>Check 1</div><div><input type='checkbox' name='status2' id='status2'>Check 2</div><div class='alert message-submit'></div></form>";
  displayConfirmation(myHtml, 'Dialog Box');
};


function displayConfirmation(msg, msgTitle, minH, width) {
  if (msgTitle == undefined) msgTitle = 'System Message';
  if (minH == undefined) minH = 100;
  if (width == undefined) width = 435;

  if (!$("#message-dialog").length) $("<div id='message-dialog'></div>").appendTo("body");
  if (msg.match(/<.+>/) == null) msg = '<p>' + msg + '</p>';

  $("#message-dialog").html(msg);
  $("#message-dialog").dialog({
    autoOpen: true,
    title: msgTitle,
    minHeight: minH,
    width: width,
    modal: true,
    position: {
      my: "center",
      at: "center",
      of: window
    },
    draggable: false,
    buttons: [{
        text: "Accept",
        class: "btn btn-primary",
        id: "btn_accept",
        click: function() {
          saveFrm();
        }
      },
      {
        text: "Cancel",
        class: "btn btn-secondary",
        click: function() {
          $(this).dialog("close");
        }
      }
    ]
  });
}

function saveFrm() {
  var frmData = $(this).serialize(),
    submitBtn = $(this).closest('form').find(':submit'),
    messageBox = $(this).closest('form').find('.message-submit'),
    statusLen = $(this).find('input[type=checkbox]:checked').length;

  console.log(frmData);
  console.log(submitBtn);
  console.log(messageBox);
  console.log(statusLen);
  // I need all varibales above. The frmData is used for ajax call. submitBtn should select Accept button element. Message box should select hidden div and status length should check aall check boxes in the form.
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div><input type="button" name="show_btn" id="show_btn" value="Show Dialog"></div>

上面的代码将为控制台中的所有元素返回0 / undefined。如果有人知道从jquery对话框中选择这些元素的方法,请告诉我。

0 个答案:

没有答案