Jump to content

adding an eventListener to check a value


strange

Recommended Posts

I am trying to listen for the click of the button .check, and simultaneously see if the value of .guess is === to secretNumber, then change the background color to a random color.

This is what I prepared to do that:

 

document.querySelector('.check').addEventListener('click', function() {
    if (document.querySelector('.guess').value === secretNumber) {
       let paletteOne = Math.trunc(Math.random() * 256 + 1), 
           paletteTwo = Math.trunc(Math.random() * 256 + 1), 
           paletteThree = Math.trunc(Math.random() * 256 + 1);
       let colors = `rgb(${paletteOne}, ${paletteTwo}, ${paletteThree})`;
       document.querySelector('body').style.backgroundColor = colors;

It's not working. Can someone help me out?

Link to comment
Share on other sites

If the variable secretNumber is of type integer, when you check for it in the if condition with the 3 equal signs, it's going to give you false because using 3 equals checks also check the type if it's equal AND the value it its equal.

If document.querySelector('.guess').value is an input of type="text" or even if you set it to type="number", the value is always going to be type string thus giving you false when you check it with 3 equal signs. 

Try using 2 equal signs in the if condition like the following for example:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">

    <script>

        window.addEventListener('load', function(){

                let secretNumber = 5; // type integer
                document.querySelector('.check').addEventListener('click', function() {
                    if (document.querySelector('.guess').value == secretNumber) 
                    {
                       let paletteOne = Math.trunc(Math.random() * 256 + 1), 
                           paletteTwo = Math.trunc(Math.random() * 256 + 1), 
                           paletteThree = Math.trunc(Math.random() * 256 + 1);
                       let colors = `rgb(${paletteOne}, ${paletteTwo}, ${paletteThree})`;
                       document.querySelector('body').style.backgroundColor = colors;

                     }
                     else{
                        console.log('no');
                     }    

            	});

        });

    </script>


</head>
<body>

<input class="guess" type="text"/>
<button class="check">Check</button>

</body>
</html>

To use 3 equal signs in the if condition, set secretNumber = '5'; 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...