skip to Main Content

I’m trying to create a textbox where if you submit the correct answer, the textbox’s background turns green, and red for the incorrect answer. However, nothing seems to happen for both options.

document.querySelector('form').addEventListener('submit', function(event) {
  //Stuff
  let input = document.querySelector('input[name="q"]');
  let answer = input.value.toLowerCase().trim();

  if (input.timeoutId) {
    clearTimeout(input.timeoutId);
  }

  // Compare with the correct answer
  if (answer === 'palm tree' || answer === 'a palm tree') {
    input.style.backgroundColor = '#00ff00'; // Green for correct answer
    input.timeoutId = setTimeout(function() {
      input.style.backgroundColor = '';
    }, 2000);
  } else {
    input.style.backgroundColor = '#ff0000'; // Red for incorrect answer
    input.timeoutId = setTimeout(function() {
      input.style.backgroundColor = '';
    }, 2000);
  }
  event.preventDefault();
});
<h3>
  What tree can you hold in your hand?
</h3>
<form>
  <input autocomplete="off" autofocus name="q" placeholder="Answer" type="text">
  <button type="submit">Submit</button>
</form>

Here’s all of the code, if you need it. For some reason it’s working on here, but not in github.dev. Here’s the mini trivia page: https://forharrisonbaby-turbo-umbrella-w6xrjxgqrqvfgwrg-8080.app.github.dev/index.html?q=hello. The previous code snippet is at the bottom.

<!DOCTYPE html>

<html lang="en">
    <head>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
        <style>
            body {
                background-color: #fff;
                color: #212529;
                font-size: 1rem;
                font-weight: 400;
                line-height: 1.5;
                margin: 0;
                text-align: left;
            }

            .container {
                margin-left: auto;
                margin-right: auto;
                padding-left: 15px;
                padding-right: 15px;
            }
            b1{
                padding-left:20px;
                padding-right: 100px;
                color: #ff0000;
                transition: color 10s ease-in-out, background-color 0.15s ease-in-out
            }

            b2{
                padding-right: 130px;
                color: #00ff00;
                transition: color 10s ease-in-out, background-color 0.15s ease-in-out
            }

            b3{
                padding-right: 180px;
                color: #ff0000;
                transition: color 10s ease-in-out, background-color 0.15s ease-in-out
            }

            b4{
                padding-left: 500x;
                color: #ff0000;
                transition: color 10s ease-in-out, background-color 0.15s ease-in-out
            }


            .hidden{
                visibility: hidden;
            }
            .header {
                background-color: #477bff;
                color: #fff;
                margin-bottom: 2rem;
                padding: 2rem 1rem;
                text-align: center;
            }

            .section {
                padding: 0.5rem 2rem 1rem 2rem;
            }

            .section:hover {
                background-color: #f5f5f5;
                color: #477bff;
                transition: color 10s ease-in-out, background-color 0.15s ease-in-out;
            }

            h1 {
                font-family: 'Montserrat', sans-serif;
                font-size: 48px;
            }

            h2 {
                margin-top: 0;
                margin-bottom: 0;
                padding-top: 0;
                padding-bottom: 0;
            }

            button, input[type="submit"] {
                background-color: #d9edff;
                border: 1px solid transparent;
                border-radius: 0.25rem;
                font-size: 0.95rem;
                font-weight: 400;
                line-height: 1.5;
                padding: 0.375rem 0.75rem;
                text-align: center;
                transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
                vertical-align: middle;
            }

            input[type="text"] {
                line-height: 1.8;
                width: 25%;
            }

            input[type="text"]:hover {
                background-color: #f5f5f5;
                transition: color 2s ease-in-out, background-color 0.15s ease-in-out;
            }
        </style>
        
        <title>Trivia!</title>
        <script>
            // TODO: Add code to check answers to questions
            document.addEventListener('DOMContentLoaded', function(){
                function check(id, message){
                    let button = document.querySelector(`#${id}`);
                    if (id === 'id2'){
                        button.style.backgroundColor = '#00ff00'; //green
                        //button timing
                        message.style.visibility = 'visible';
                        if (button.timeoutId) {
                            clearTimeout(button.timeoutId);
                        }
                        setTimeout(function(){
                            button.style.backgroundColor = '';
                            message.style.visibility = 'hidden';
                        }, 1000);
                    }else{
                        button.style.backgroundColor = '#ff0000'; //red
                        message.style.visibility = 'visible';
                        if (button.timeoutId) {
                            clearTimeout(button.timeoutId);
                        }
                        setTimeout(function(){
                            button.style.backgroundColor = '';
                            message.style.visibility = 'hidden';
                        }, 1000);
                    }
                }
            var message1 = document.querySelector('b1'); //Incorrect
            var message2 = document.querySelector('b2'); //Correct
            var message3 = document.querySelector('b3'); //Incorrect
            var message4 = document.querySelector('b4'); //Incorrect
            document.querySelector('#id1').addEventListener('click', function(){
                check('id1', message1);
            });
            document.querySelector('#id2').addEventListener('click', function(){
                check('id2', message2);
            });
            document.querySelector('#id3').addEventListener('click', function(){
                check('id3', message3);
            });
            document.querySelector('#id4').addEventListener('click', function(){
                check('id4', message4);
            })
        });
        </script>
    </head>
    <body>
        <div class="header">
            <h1>Trivia!</h1>
        </div>
        <div class="container">
            <div class="section">
                <h2> Part 1: Multiple Choice </h2>
                <hr>
                <!-- TODO: Add multiple choice question here -->
                <h3>
                    What does the Mushroom tell the other Mushroom when they're the only Mushrooms in their world?
                </h3>
                <button id="id1"> I'm a Fun Guy!</button>
                <button id="id2">There's 2 mushroom?</button>
                <button id="id3"> Let me trufle over to you.</button>
                <button id="id4"> "Sigh". Lets wallop on the pizza-ria...</button>
                <div>
                    <b1 class="hidden">Incorrect</b1>
                    <b2 class="hidden">Correct</b2>
                    <b3 class="hidden">Incorrect</b3>
                    <b4 class="hidden">Incorrect</b4>
                </div>
            </div>
            <div class="section">
                <h2>Part 2: Free Response</h2>
                <hr>
                <!-- TODO: Add free response question here -->
            <h3>
                What tree can you hold in your hand?
            </h3>
            <form>
                <input autocomplete="off" autofocus name="q" placeholder="Answer" type="text">
                <button type="submit">Submit</button>
            </form>
            <script>
                document.querySelector('form').addEventListener('submit', function(event) {
                    event.preventDefault();
                    //Stuff
                    let input = document.querySelector('input[name="q"]');
                    let answer = input.value.toLowerCase().trim();

                    if (input.timeoutId) {
                        clearTimeout(input.timeoutId);
                    }

                    // Compare with the correct answer
                    if (answer === 'palm tree' || answer === 'a palm tree') {
                        input.style.backgroundColor = '#00ff00'; // Green for correct answer
                        input.timeoutId = setTimeout(function() {
                            input.style.backgroundColor = '';
                        }, 2000);
                    } else {
                        input.style.backgroundColor = '#ff0000'; // Red for incorrect answer
                        input.timeoutId = setTimeout(function() {
                            input.style.backgroundColor = '';
                        }, 2000);
                    }
                });
            </script>
            </div>
        </div>
    </body>
</html>

2

Answers


  1. Chosen as BEST ANSWER

    The code works if you run it on Stack Overflow, but not in Github.dev. The problem is probably something on their end.


  2. You can use the build-in form validation. Set the required and pattern attributes on the input element. If the value is invalid the callback for the invalid event will be called. If the value is valid the form will submit and the submit callback will be called.

    document.forms.form01.addEventListener('submit', function(event) {
      event.preventDefault();
      let input = event.target.q;
    
      input.classList.add('valid');
    
      input.timeoutId = setTimeout(function() {
        input.classList.remove('valid');
      }, 2000);
    });
    
    document.forms.form01.addEventListener('invalid', function(event) {
      event.preventDefault();
      let input = event.target;
    
      input.classList.add('invalid');
    
      input.timeoutId = setTimeout(function() {
        input.classList.remove('invalid');
      }, 2000);
    }, true);
    .invalid {
      background-color: red;
    }
    
    .valid {
      background-color: green;
    }
    <h3>
      What tree can you hold in your hand?
    </h3>
    <form name="form01">
      <input autocomplete="off" autofocus name="q" placeholder="Answer"
      type="text" pattern="(a )?palm tree" required>
      <button type="submit">Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search