How to make a button apear when scored correctly on a test

So I made a js test with the following code.

`var formElement = document.forms['quizForm'];

formElement.onsubmit = function submitAnswers(){
var total = 5;
var score = 0;

// Get User Input
var q1 = document.forms["quizForm"]["q1"].value,
    q2 = document.forms["quizForm"]["q2"].value,
    q3 = document.forms["quizForm"]["q3"].value,
    q4 = document.forms["quizForm"]["q4"].value,
    q5 = document.forms["quizForm"]["q5"].value;

// Validation
for(i = 1; i <= total;i++){
	if(eval('q'+i) === null || eval('q'+i) === ''){
		alert('You missed question '+ i);
		return false;
	}
}

// Set Correct Answers
var answers = ["b","a","d","b","d"];

// Check Answers
for(i = 1; i <= total;i++){
	if(eval('q'+i) === answers[i - 1]){
		score++;
	}
}

// Display Results
var results = document.getElementById('results');
results.innerHTML = '<h3>You scored <span>'+score+'</span> out of <span>'+total+'</span></h3>';
return false;

}

how would I make it if I score 3/3. It will show a button, after the user submits the test with a seperate button.

Hey @anon70439135,

Assuming that the results variable is the score a user gets, we can use an if statement to see if it matches your required score and then control the visibility of a button.

HTML:

...
<button id="show-after-submit" style="display: none;">Click me after getting your scores!</button>
...

JS:

... 
// all your code

// Display Results
var results = document.getElementById('results');
results.innerHTML = '<h3>You scored <span>'+score+'</span> out of <span>'+total+'</span></h3>';
return false;

if (score === total) {
   // score === total means that the user got all questions correct out of all the total questions
   document.getElementById("show-after-submit").style.display = "block";
} else {
   // user did not get all questions correct
   document.getElementById("show-after-submit").style.display = "none";
}

The else block of the if statement isn’t exactly necessary, but it helps in hiding the button in case a variable somehow causes the button to be visible.

Hope this helps!

1 Like

I’ll try it out @khalby786

Thanks

1 Like