javascript(Vanilla) - 如何在显示警报后阻止HTML表单发布

时间:2018-04-26 03:52:11

标签: javascript html forms validation

我已经通过一些验证在html中进行了测验,我想要进行的下一步是在javascript中对此测验进行评分。我的评分系统很好,按预期工作,但我想阻止表格发布到result.html,如果他们在测验中得分为0。发生这种情况时,我设法显示警报,但按OK后,结果页面仍会加载。 (结果页面现在为空)。我已经尝试过查看window.history.back,以及preventDefault,但我无法帮助,但我认为我不理解其中一个或两个的语法。我想显示警报,然后用户停留在同一页面上。我也想留在vanilla javascript中,以及避免使用内联的东西。谢谢:))

这是我的测验表格:

<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>

这是我的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;

2 个答案:

答案 0 :(得分:4)

要改变两个地方:

checkscore函数本身在失败时必须返回false:

if (score==0) {
  alert('error');
  return false;
}

然后表单提交本身需要返回函数的返回值:

quiz.onsubmit=function(){
  return checkscore();
}

我知道您试图避免编写内联代码,但如果上述更改是内联的,则更容易看出差异:

<form ... onsubmit="checkscore();"> <-- this doesn't work

<form ... onsubmit="return checkscore();"> <-- this works

答案 1 :(得分:1)

当你这样做时,你的功能在用户提交表单时被调用。此时,它将完成该功能,然后继续提交,除非被告知不要。

如果您的函数返回false,则应取消当前正在进行的提交,并将用户保留在页面上。

尝试更改:

  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;
  }

分为:

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.");
    return false;
}