Home > database >  Check the answer
Check the answer

Time:05-10

I try to see if the word entered in the form is the correct one. If it is correct then I open another page and otherwise I will get an error message, but I don't know how to make the script for this. Also I don't want to use a submit button.

<form id="form">
    <input type="text" name="inputBox" placeholder="Enter your answer"><br> 
</form>

CodePudding user response:

Try this: In this code I check with the key event, if I press enter I call and ask if the answer is "Hello" is correct and I open another page, otherwise I send an alert with an error

<form id="form">
    <input id="MyEnter" type="text" name="inputBox" placeholder="Enter your answer"><br> 
</form>

<script>
var myenter = document.getElementById("MyEnter");
myenter.addEventListener("keypress", function(event) {
  if (event.key === "Enter") {
    event.preventDefault();
    var answer = 'Hello'
    var mytext = document.getElementById("MyEnter").value;
    if (mytext==answer) {
        alert('opening another page');
        window.open("https://www.google.com");
    }else{
        alert("Incorrect answer");
    }
  }
});
</script>

CodePudding user response:

const input = document.querySelector('input');
const error = document.querySelector('p.error');
const woohoo = document.querySelector('p.woohoo');

const correctAnswer = 'foo bar baz';

const handleInput = (condition) => {
    if (condition) {
        error.style.display = 'block';
        woohoo.style.display = 'none';
        return;
    }

    error.style.display = 'none';
    woohoo.style.display = 'block';

    window.open('https://google.com');
};

input.addEventListener('keyup', () => handleInput(input.value !== correctAnswer));
<form id="form">
    <input type="text" name="inputBox" placeholder="Enter your answer" />
    <p  style="color: red; display: none">Incorrect</p>
    <p  style="color: green; display: none">Correct</p>
</form>

  • Related