How to Iterate Checkbox and Foreach in PHP and JS

Asked

Viewed 49 times

1

I have a foreach that shows the data received from the database, I want to display the data only if the checkbox is checked, but the field display works only in the first iteration of Foreach, follow the code below:

<script>
 function myFunction() {
     var checkBox = document.getElementById("VisualizarCampos");
     var conteudo = document.getElementById("Conteudo");
     if (checkBox.checked == true) {
        conteudo.style.display = "block";
     } else {
        conteudo.style.display = "none";
     }
 }
</script>
<?php foreach ($certificados as $data): ?>
  <?php $i++; ?>
   <header>
     <strong> <?php echo $i; ?> - Preencha os campos para editar os certificados</strong>
   </header>
    <div class="form-check">
      <label><input style="margin-left: 16px" type="checkbox"
            class="input-lg"
            id="VisualizarCampos" name="VisualizarCampos[<?php echo $i ?>]"                                                                 onclick="myFunction(this)">Editar</input></label>
    </div>
    <div id="Conteudo" style="display: none;margin-left: 15px">
       <input style="display: none" type="text" class="input-lg"
       value="<?php echo $data['id'] ?>" name="id">
       <input type="text" class="input-lg"
       value="<?php echo $data['nome_curso'] ?>" name="nome_curso">
       <input style="display: none" type="text" class="input-lg"
       value="<?php echo $data['id'] ?>" name="id">
       <input type="text" class="input-lg"
       value="<?php echo $data['nome_curso'] ?>" name="nome_curso">
    </div>
    <?php endforeach; endif; ?>

Below follows the example, I have two checkbox marked but only one is displaying inserir a descrição da imagem aqui

1 answer

0


The input id needs to be unique, you are using the same id every time. Tries to generate a unique id for each repetition with a variable and pass this id as parameter to the function.

 var checkBox = document.getElementById("VisualizarCampos");
 var conteudo = document.getElementById("Conteudo"); 

 <input style="margin-left: 16px" type="checkbox" class="input-lg"id="VisualizarCampos" 
 name="VisualizarCampos[<?php echo $i ?>]" onclick="myFunction(this)">Editar</input></label>

 <div id="Conteudo" style="display: none;margin-left: 15px">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.