This code is supposed to ask the user for an input and return incorrect or correct depending on the string that was submitted(the correct answer is "Aconcagua"). When running it and submitting neither of those answers is printed into the screen. I am pretty new to javascript and HTML.
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>Trivia!</title>
<script>
function wrong2()
{
document.querySelector('#2solution').innerHTML = "Incorrect.";
document.querySelector('#input').style.backgrounColor = 'red';
}
function right2()
{
document.querySelector('#2solution').innerHTML = "Correct!";
document.querySelector('#input').style.backgrounColor = 'green';
}
a = "Aconcagua";
document.querySelector('#form').addEventListener('submit', function(event){
if (document.querySelector('#input').value.localeCompare(a) == 0)
{
right2();
}
else
{
wrong2();
}
event.preventDefault();
});
</script>
</head>
<body>
<div class="header">
<h1>Trivia!</h1>
</div>
<div class="section">
<h2>Part 2: Free Response</h2>
<hr>
<h3>What is the highest mountain in South America?</h3>
<form action="" id="form">
<input id="input" type="text">
<button id="b" type="sumbit">Submit</button>
</form>
</div>
<h2 id="2solution"></h2>
</div>
</body>
</html>
2
Answers
You’re missing parentheses () which are necessary to call the functions. right2() and wrong2().
Without (), they are just treated as references to the functions rather than function calls.
Corrected code:
The DOMContentLoaded fires only once the HTML page has been fully parsed, so this ensures your form has loaded before the event.
Here is a working example of your code. First you have a closing "/div" without an opening "div". You also have a typo on BackgroundColor (witout d). It is better to define const in the beginning of your javascript (unless sometimes necessary). Also open full page to see colored background when using snippet. Besides these errors your code could have worked 🙂