Search code examples
javascripthtmlfunctionif-statementsubmit-button

Why is only one if statement output when I have put different ones for different conditions?


I made a code that has some simple math problems. When the user has pressed submit the if statements would determine whether the text box is null or has some input. I put an if statement for that if the user got the question correct it would document. write correct and if it is null it would write not answered and so on. Instead of that, it outputs correct no matter if the text box is left empty or if they got the answer wrong. I know that document.write is frowned upon but I'm a beginner so please help me.

document.getElementById("q1");
document.getElementById("q2");
document.getElementById("q3");
document.getElementById("q4");
document.getElementById("a1");
document.getElementById("a2");
document.getElementById("a3");
document.getElementById("a4");
document.getElementById("submit");

function check() {

	if((q1.value == 6084) || (q1.value == 6,084)){
		document.write("<b>" + "1. Correct" + "</b>");
	} else if(q1.value.length == 0){
		document.write("<b>" + "1. Not Answered" + "</b>");
	}
	else {
			document.write("<b>" + "1. Incorrect" + "</b>");
		}
	
}
<!DOCTYPE html>
<html>
<head>
	<title>Quiz1</title>
</head>
<body>
<h1 align = "center">Math Test 📃✍</h1>
<h3 id = "q1">Question 1 : 78 * 78 = ?</h3>
<input id = "a1" type = "text" required>
<h3 id = "q2">Question 2 : (100 / 6) + 45 = ?</h3>
<input id = "a2" type = "text">
<h3 id = "q3">Question 3 : 87 + 123 = ?</h3>
<input id = "a3" type = "text">
<h3 id = "q4">Question 4 : 100 - 23 = ?</h3>
<input id = "a4" type = "text">
<br>
<br>
<button id = "submit" onclick = "check()">I'm Done!</button>



</body>
</html>


Solution

  • Bergi's comment on the question gets at the root cause of this problem, so I'm going to take a stab at helping to solve it.

    First of all, if all of these answers are going to be numbers, you should use number type inputs. That will prevent users from typing in non-numerical characters, which will mean you'll only have to worry about 6084 and not 6,084, so you can go ahead and remove the || (q1.value == 6,084).

    Secondly, I don't see you assigning the variable q1 anywhere. Did you mean to assign the result of document.getElementById("a1") to the variable q1? If you did, then you need to assign it by writing const q1 = document.getElementById("a1"). If that still doesn't work, put console.log(q1) in the first line of the check function to see what it is exactly that you're working with.

    Alternatively, if you want to keep your ids and variable names the same. use const a1 = document.getElementById("a1") and then change every reference to q1 in the check function to a1.