'HTML/CSS/JS: 'Show' answer on button press
I am creating a quiz for my webpage. Currently, I have a function working on the first question. Where a button will say "Show Solution". Once clicked, it will show the element. Currently the button doesn't change the button text to "Hide Solution" once it has been displayed.
The main problem is that i have multiple questions. And when i click show solution it will show the first question. I know that the function is linked to that function, but I do not want to copy the function multiple times and change the IDs to answer1, answer2 etc...
I have looked at posts on google/stack and YouTube videos and I just don't understand it really.
Here is my code
function show_hide()
{
var myAnswer = document.getElementById('answer');
var displaySetting = myAnswer.style.display;
var quizButton = document.getElementsByClassName('quiz-button');
if(displaySetting=="inline-block"){
myAnswer.style.display = 'none';
quizButton.innerHTML = 'Show Answer';
}
else
{
myAnswer.style.display = 'inline-block';
quizButton.innerHTML = 'Hide Answer';
}
}
.quiz-question{
margin-bottom: 10px;
text-align: left;
font-size: 15px;
color: #f44336;
font-weight: 400;
}
.quiz-button{
display: inline-block;
text-decoration: none;
color: #111;
border: 1px solid #f44336;
padding: 5px 5px;
font-size: 13px;
background: transparent;
position: relative;
cursor: pointer;
}
.quiz-button:hover{
color: #fff;
background: #f44336;
transition: 0.5s;
}
#answer{
display: none;
}
<div class="part-content quiz">
<h2>Chapter 1.1 End of Topic Quiz</h2>
<p>
The following quiz is meant to reinforce your understanding of the material presented above.
</p>
<!-- Question 1 Start -->
<h4 class="quiz-question">1. What is a statement? </h4>
<button onclick="show_hide()" class="quiz-button">Show Solution</button>
<p id="answer">
A <b>statement</b> is an instruction in a computer program that tells the computer to perform an action.
</p>
<br><br><hr>
<!-- Question 1 End -->
<!-- Question 2 Start -->
<h4 class="quiz-question">2. What is a function? </h4>
<button onclick="show_hide()" class="quiz-button">Show Solution</button>
<p id="answer">
A <b>function</b> is several statements that are executed sequentially.
</p>
<br><br><hr>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
