Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

338
Vistas
Passing a variable into a javascript function in PHP to make specific divs hide or show?

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?

enter image description here

Thanks!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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='#'>
 .....
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda