javascript - javascript (Vanilla) - How to prevent HTML form post after an alert is shown
问题描述
I have made a quiz in html with some validation, and the next step I would like to undertake is to score this quiz in javascript. My scoring system is all well and works as intended, but I'd like to prevent the form from posting to result.html IF they score 0 on the quiz. I have managed to display an alert when this happens, but upon pressing OK, the result page loads anyway. (The result page is empty for now). I've tried looking at both window.history.back, as well as preventDefault, but I can't help but to think I am not understanding syntax for one or both of these things. I'd like the alert to show, and then the user stay on the same page. I'd also like to stay within vanilla javascript, as well as avoiding inline stuff. Thanks :)
Here is my quiz form:
<form name="quiz" id="quiz" method="post" action="result.html">
<fieldset>
<legend>Student Details</legend>
<p><label for="firstName">Name: </label>
<input type="text" name="firstName" id="firstName" placeholder="First" maxlength="25" required="required" pattern="^[A-Za-z -]+$" title="Please use only letters/hyphens/spaces." />
<input type="text" name="lastName" id="lastName" placeholder="Last" maxlength="25" required="required" pattern="^[A-Za-z -]+$" title="Please use only letters/hyphens/spaces." /></p>
<p><label for="studentID">Student ID: </label>
<input type="text" name="studentID" id="studentID" placeholder="e.g. s123456789" required="required" pattern="(\w{1}\d{6}(\d{3})?)" title="Please enter either 7 or 10 characters, beginning with the letter 's'." /></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 1</legend>
<p><label for="answer1">In what year was the SSH-1 protocol released?</label><br/><br/>
<input type="text" name="answer1" id="answer1" pattern="[0-9]{1,4}" placeholder="e.g. 2018" required="required" title="Please enter a year with up to 4 digits." /></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 2</legend>
<p><label>Who developed the SSH-1 protocol?</label><br/><br/>
<input type="radio" name="answer2" id="answer2_1" value="wuXian" required="required" /><label for="answer2_1">Wu Xian</label><br/>
<input type="radio" name="answer2" id="answer2_2" value="mohammadHaddad" /><label for="answer2_2">Mohammad Haddad</label><br/>
<input type="radio" name="answer2" id="answer2_3" value="tatuYlonen" /><label for="answer2_3">Tatu Ylönen</label><br/>
<input type="radio" name="answer2" id="answer2_4" value="fredrikJohannsen" /><label for="answer2_4">Fredrik Jöhannsen</label></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 3</legend>
<p><label>Select as many SSH <em>protocols</em> as you see.</label><br/><br/>
<input type="checkbox" name="answer3_1" id="answer3_1" value="ssh2" /><label for="answer3_1">SSH-2</label><br/>
<input type="checkbox" name="answer3_2" id="answer3_2" value="openBSD" /><label for="answer3_2">OpenBSD</label><br/>
<input type="checkbox" name="answer3_3" id="answer3_3" value="ssh1" /><label for="answer3_3">SSH-1</label><br/>
<input type="checkbox" name="answer3_4" id="answer3_4" value="openSSH" /><label for="answer3_4">OpenSSH</label></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 4</legend>
<p><label for="answer4">SSH is a: </label><br/><br/>
<select name="answer4" id="answer4" form="quiz" required="required">
<option value="">Please select...</option>
<option value="applicationLayer">Application layer protocol</option>
<option value="transportLayer">Transport layer protocol</option>
<option value="internetLayer">Internet layer protocol</option>
<option value="linkLayer">Link layer protocol</option>
</select></p>
</fieldset>
<br/>
<fieldset>
<legend>Question 5</legend>
<p><label for="answer5">Click on the flag of the country where the SSH-1 protocol was first developed, and then click Submit.</label><br/><br/>
<img src="images/flags.jpg" width="400" height="400" alt="Scandinavian Flags" usemap="#flagsMap" />
<input type="text" name="answer5" id="answer5" value="" readonly="readonly" required="required" /><br/><br/>
<map name="flagsMap">
<area shape="rect" coords="0,0,200,200" alt="Finland" href="#bottom" onClick="document.forms['quiz'].answer5.value='Finland'"/>
<area shape="rect" coords="200,0,400,200" alt="Iceland" href="#bottom" onClick="document.forms['quiz'].answer5.value='Iceland'"/>
<area shape="rect" coords="0,200,200,400" alt="Norway" href="#bottom" onClick="document.forms['quiz'].answer5.value='Norway'"/>
<area shape="rect" coords="200,200,400,400" alt="Sweden" href="#bottom" onClick="document.forms['quiz'].answer5.value='Sweden'"/>
</map></p>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<input type="submit" />
</fieldset>
</form>
And here is my javascript:
"use strict";
function goBack() {
window.history.back();
}
function checkScore() {
var score = 0;
var ans1 = document.getElementById("answer1");
if (ans1.value == "1995") {
score = score + 2;
}
var ans2_3 = document.getElementById("answer2_3");
if (ans2_3.checked == true) {
score = score + 2;
}
var ans3_1 = document.getElementById("answer3_1");
var ans3_2 = document.getElementById("answer3_2");
var ans3_3 = document.getElementById("answer3_3");
var ans3_4 = document.getElementById("answer3_4");
if (ans3_1.checked == true && ans3_2.checked == false && ans3_3.checked ==
true && ans3_4.checked == false) {
score = score + 2;
}
var ans4 = document.getElementById("answer4");
if (ans4.value == "applicationLayer") {
score = score + 2;
}
var ans5 = document.getElementById("answer5");
if (ans5.value == "Finland") {
score = score + 2;
}
if (score == 0) {
alert("You have attempted to submit this quiz, but you have scored 0/10.
Please reconsider your answers, and try to raise your score.");
goBack;
}
}
function init() {
var quiz = document.getElementById("quiz");
quiz.onsubmit = checkScore;
}
window.onload = init;
解决方案
Two places to change:
The checkscore function itself has to return false when fails:
if (score==0) {
alert('error');
return false;
}
Then the form submit itself needs to return the return value of the function:
quiz.onsubmit=function(){
return checkscore();
}
I know you are trying to avoid writing inline code, but if the above changes were made inline, it's easier to see the difference:
<form ... onsubmit="checkscore();"> <-- this doesn't work
<form ... onsubmit="return checkscore();"> <-- this works
推荐阅读
- html - 将第二行链接与第一行的开头对齐
- html - 如何修复图像 src
- python - 表单模板中调整的清理功能不会将错误传递给表单
- javascript - 如何将 .NET 控制器中的数据显示到 React 视图?
- vue.js - VUEJS 检查用户是否喜欢帖子
- python - 403 禁止错误。无法访问此站点
- c# - VS 2008 MULTI LAYERS C# 项目在打开时出错
- c# - 将 NSubstitute 导入 Unity 项目
- sql - `DB2`中MS-SQL`QUOTENAME`的等价物是什么
- sql-server - 将递归存储过程包装在另一个过程中时出现“超出最大嵌套级别”错误