忽略了jQuery对话框按钮,继续提交表单
P粉832212776
2023-08-15 12:55:00
<p>我有以下的表单代码和javascript代码如下所示。问题是当执行到<code>validateDialogForm()</code>时,如果满足某些条件,会显示一个jquery对话框。我确实能够看到对话框出现了几秒钟,但它不会停留在那里,表单仍然继续提交。我希望表单在一段时间内暂停,只有当用户点击<code>保存</code>按钮时才提交。我尝试在<code>validateDialogForm()</code>函数结束前加上<code>return false;</code>,以阻止表单提交,但当我点击对话框的保存按钮时,它不会继续提交表单,而是保持原样。我在这里做错了什么?以下代码的当前状态是,无论jquery对话框如何,表单都将继续提交。(为了清晰起见,删除了很多不相关的代码)</p>
<p><br /></p>
<pre class="brush:js;toolbar:false;">$('#checklist_dialog').hide();
function validateDialogForm() {
$('#checklist_dialog').show();
var isConfirmed = false;
//STEP:1 Check if option B is selected.
var selectedVal = "";
var selected = $("input[type='radio'][name='sampleChoice']:checked");
if (selected.length > 0) {
selectedVal = selected.val();
console.log("Selected Option is " + selectedVal);
}
if (selectedVal === "choiceB") {
if ($("#choiceBstatus").val() === "true") {
//show the dialog box
$('#checklist_dialog').dialog({
modal: true,
maxWidth: 600,
maxHeight: 500,
width: 600,
height: 500,
overlay: {
opacity: 0.7,
background: "black"
},
buttons: {
"SAVE": function() {
$(this).dialog('close');
alert("Inside SAVE button which is clicked");
$("#choiceBstatus").val("false");
//isConfirmed = true;
return true;
},
"CANCEL": function() {
$(this).dialog('close');
alert("You must complete / save the checklist before saving your form!");
// return false;
}
}
});
/* e.preventDefault();
return false; */
} //end of if($("#choiceBstatus").val() == true ){
if ($("#choiceBstatus").val() === "false") {
// return true;
}
} //end of if(selectedVal === "choiceB"){
//return false;
/* if(isConfirmed){
return true;
}
else {
return false;
}
*/
}</pre>
<pre class="brush:html;toolbar:false;"><form id="orderForm" action="/mywebsite/order.htm" method="POST" onsubmit="return (validateOrderForm(this) && validateDialogForm())">
<input id="choiceBstatus" name="choiceBstatus" type="hidden" value="true">
<div id="ownerDisplayFields" style="visibility: visible;">
<table class="noPrint">
//some divs
</tbody>
</table>
</div>
<div id="pManualTitle" style="display: block">
<table class="noPrint">
<tbody>
</tbody>
</table>
</div>
<div id="checklist_dialog" title="New Title" style="display: none;">
<p>Checklist 1 goes here</p>
<p>Checklist 2 goes here </p>
</div>
<table class="noPrint">
<tbody>
<tr>
<td align="center"><br>
<input class="button" type="submit" name="save" value="Save"> - <input class="button" type="submit" name="cancel" value="Cancel" onclick="bCancel = true;">
</td>
</tr>
</tbody>
</table>
<div></div>
</form></pre>
<p><br /></p>
如评论中所提到的,当对话框显示时,您需要阻止表单提交,因为对话框不会阻塞UI。除非您停止它,否则它将继续提交。在您按下对话框中的按钮后,您可以真正提交表单。
现在的棘手之处在于,当您真正提交表单时,这也会再次触发
onsubmit
函数!一个好的方法是设置一个标志。请参见下面的伪代码,它应该基本上做到了您想要的。