whats wrong with this code plzz help | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

whats wrong with this code plzz help

<!DOCTYPE html> <html> <head> <title>Conditional statements</title> </head> <body> <p>Enter the name of your favorite type of animal that stars in a cartoon:</p> <form name="frmAnimal"> <input type="text" name="txtAnimal" id="txtAnimal" ><br> <input type="button" value="Check animal" id="check"> </form> <p>Note that rabbit, coyote, and mouse will all get different responses.</p> <script> function checkAnimal() { switch ( document.getElementById( "txtAnimal" ).value.toLowerCase() ){ case "rabbit": alert( "Watch out, it's Elmer Fudd!" ); break; case "coyote": alert( "No match for the road runner - meep meep!" ); break; case "mouse": alert( "Watch out Jerry, here comes Tom!" ); break; default : alert("Are you sure you picked an animal from a cartoon?"); } } document.getElementById( "check" ).onclick= checkAnimal(); </script> </body> </html>

29th Aug 2020, 10:14 AM
xavi
14 Answers
+ 3
last line document.getElementById("check").onlick = checkAnimal() Don't call your function. checkAnimal then parenthesis () It mean your code calls that function immediately. So put your function name without parenthesis. Like document.getElementById("check"). onclick = checkAnimal;
29th Aug 2020, 10:21 AM
Kelvin Paul
Kelvin Paul - avatar
+ 3
🤦‍♂️ save you code and then share your code because it make really simple for us to short out errors
29th Aug 2020, 10:19 AM
Ayush Kumar
Ayush Kumar - avatar
+ 2
okay dude
30th Aug 2020, 7:10 PM
xavi
+ 1
thank you bro
29th Aug 2020, 10:22 AM
xavi
+ 1
Why dont you cache the DOM first and then write the logic cause this has happened with me multiple times where nothing is wrong and it doesn't work.
29th Aug 2020, 10:22 AM
Kunsh-Tyagi
Kunsh-Tyagi - avatar
+ 1
I think you got the correct solution. Isn't it ?
29th Aug 2020, 10:23 AM
Kelvin Paul
Kelvin Paul - avatar
+ 1
can i call a function without parenthesis
29th Aug 2020, 10:24 AM
xavi
+ 1
Why dont you add an EventListener to id check
29th Aug 2020, 10:25 AM
Kunsh-Tyagi
Kunsh-Tyagi - avatar
+ 1
thank you dude
29th Aug 2020, 10:31 AM
xavi
0
yes it works but how
29th Aug 2020, 10:23 AM
xavi
0
xavi Nope. Without parenthesis that doesn't means that a function call. Copying the blue print of that particular function definition. into that position. When you click that button the function will be triggered
29th Aug 2020, 10:27 AM
Kelvin Paul
Kelvin Paul - avatar
0
You can also add a function event via addEventListener method. HTMLElement.addEventListener("event type", functionName, {userCapture,...})
29th Aug 2020, 10:30 AM
Kelvin Paul
Kelvin Paul - avatar
0
Welcome bro 😊👍
29th Aug 2020, 10:31 AM
Kelvin Paul
Kelvin Paul - avatar
0
Xavi make it a sololearn code before you post it's more readable, just advise.
30th Aug 2020, 6:52 PM
Abbakar_ah!!!
Abbakar_ah!!! - avatar