I am trying to create a simple FAQ page where the user clicks the question and the answer appears below it (or hides it, if clicked again).
I got it working up to a point where all the questions will show the answer labeled "ans1". But I would like to pass a variable from each question into the function so it makes the associated answer appear. Question 1 will show Answer 1, Question 2 -> Answer 2, and so on.
My function...
function theAnswer() {
var x = document.getElementById("ans1");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
PHP...
<?php
$answer = 1;
foreach($faqArray as $faq) {
?>
<div class='product_container'>
<div class='product_cell'>
<a onclick="theAnswer()" href='#'>
<?php echo $faq[0];?>
</a>
</div>
</div>
<div class="answer" id="ans<?php echo $answer;?>" style="display:none;">
<p><?php echo $faq[1];?></p>
</div>
<?php
$answer = $answer 1;
} ?>
If I put a variable in the onclick="theAnswer()" that dictates the associated div, how can I get the function to perform the desired result?
Thanks!
CodePudding user response:
Your PHP code is run server-side and your Javascript code is run client-side. So the two codes cant interact with each other. I recommend hiding your element with CSS use something like this:
.hide{
display : none
}
and set your your div to hide like this
<div class='hide' id='answer-<?php echo $answer;?>'> .... </div>
and you would remove hide from your element's class list like this
function theAnswer(num){
answer = document.querySelector('#answer-' num)
answer.classList.remove('hide')
}
in your php code youd have to put in the value
.....
<a onclick="theAnswer('<?php echo $answer;?>')" href='#'>
.....