当提交按钮上的确认命令返回 false 时,希望表单不提交

问题描述 投票:0回答:1

我有一个简单的表格。当按下表单的提交按钮时,如果用户真的想提交表单,我想要一个 JS 确认语句来捕获。对话框出现。如果在确认对话框中按下取消,则 confirm() 会返回 false,但表单仍会提交。其他按钮可以提交表单。我做错了什么?

<!DOCTYPE html>
<html>
<head>
<style>
.bg2 {background-color: #E1EBF2;}
html, body {
  color: #536482;
  background-color: #F5F7FA;
  label: font-weight: 800;
}
</style>
<script>
function confirm_check() {
    return confirm('Does this post conform to the board rules? If unfamiliar with the board rules, click Cancel then read the Board rules on the navigation bar. If it complies, submit the form again and select OK.')
}
</script>
</head>
<body>
<title>Posting form</title>
<h1>Posting form</h1>
<div class="bg2">
<form action="./thanks.html" method="get">

<div>

<dl>
<dt><label for="subject">Subject:</label></dt>
<dd><input type="text" name="subject" id="subject" size="45" maxlength="120" tabindex="2" value="" class="inputbox autowidth" /></dd>
</dl>
</div>

<div>
<textarea name="message" id="message" rows="15" cols="76" tabindex="4" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onfocus="initInsertions();" class="inputbox" style="position: relative;">
</textarea>
</div>
<input type="submit" accesskey="k" tabindex="7" name="save" value="Save draft" class="button2">&nbsp;
<input type="submit" tabindex="5" name="preview" value="Preview" class="button1">&nbsp;
<input type="submit" accesskey="s" tabindex="6" name="post" onclick="confirm_check();" value="Submit" class="button1 default-submit-action">&nbsp;
        
</form>

</body>
</html>
javascript confirm
1个回答
0
投票

你需要

onclick="return confirm_check();"
让它与内联事件处理程序一起工作(为此返回
false
阻止默认操作)。只调用
confirm_check()
忽略返回值。

要让

confirm
出现在任何提交表单的方法中(例如,在
<input>
中按回车键或单击 3 个提交按钮中的任何一个),您应该处理
submit
事件。使用内联事件处理程序,您可以删除
onclick
并在
onsubmit="return confirm_check();"
元素上使用
<form>

但是,使用内联事件处理程序并不是现代 JavaScript 的最佳实践。你应该更喜欢

addEventListener
并使用
event.preventDefault()
代替。

该代码看起来像这样(首先删除所有内联事件处理程序):

document.querySelector('.default-submit-action').addEventListener('click', e => {
    if (!confirm_check()) e.preventDefault();
});
© www.soinside.com 2019 - 2024. All rights reserved.