Javascript redirect on form submit depending on input

前端 未结 1 1348
既然无缘
既然无缘 2021-01-05 10:56

I\'m working on a simple javascript quiz, and I can\'t for the life of me get Javascript to submit the form and open the result in the same page, regardless of whether I use

相关标签:
1条回答
  • 2021-01-05 11:06

    Five things:

    1. Remove the target attribute of form entirely. The default is the same window. Although it doesn't really matter, because:

    2. Cancel the submit event by returning false in your onSubmit, since you're handling the form in your own code. One easy way to do this is have your function return false, and in the onSubmit, return the result of the call.

    3. This line is incorrect:

      var response = document.getElementById('answer').value;
      

      form elements don't have a value. You'd want to put the id on the input type="text" element instead.

    4. The href on location is not a function, it's a property. You just assign to it (or just assign directly to location).

    5. This one's a bit subtle: Because you have a global function called answer, and you have an element with an id "answer", there's a conflict: Both want to end up as properties of the window object (one of many reasons not to use old DOM0 onxyz attributes — or global functions, come to that). So you need to change the name of one of them, e.g., change the function to checkAnswer or similar.

    So:

    <form onSubmit="return checkAnswer();">
    <input id="answer" type="text" maxlength="55" class="box" autofocus />
    <input type="submit" class="submit" value="SUBMIT" />
    </form>
    

    And:

    function checkAnswer(){
        var response = document.getElementById('answer').value;
        if (response == "correctanswer")
            location = 'right.html';
        else
            location = 'wrong.html';
        return false;
    }
    

    Full Example: Live Copy | Live Source

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>JS Bin</title>
    </head>
    <body>
      <form onSubmit="return checkAnswer();">
      <input id="answer" type="text" maxlength="55" class="box" autofocus />
      <input type="submit" class="submit" value="SUBMIT" />
      </form>
      <script>
      function checkAnswer(){
          var response = document.getElementById('answer').value;
          if (response == "correctanswer")
              location = 'http://jsbin.com/ukifoh/1'; // 'right.html';
          else
              location = 'http://jsbin.com/ukifoh/2'; // 'wrong.html';
          return false;
      }
      </script>
    </body>
    </html>
    

    I would recommend always using consistent, useful code indentation, and I'm a big fan of always using blocks, not just statements, with control structures.

    0 讨论(0)
提交回复
热议问题