Pick up line data with checkbox marked

Asked

Viewed 71 times

2

I have the code below and I want the array nome contains only the names of the lines that have the checkbox cb marked.

<form action="" method="post">
    <table>
        <tr>
            <td><input type="checkbox" name="cb[]" id="cb1" value="1"></td>
            <td><input type="text" name="nome[]" id="nome1"></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="cb[]" id="cb2" value="1"></td>
            <td><input type="text" name="nome[]" id="nome2"></td>
        </tr>
        <tr>
            <td><input type="checkbox" name="cb[]" id="cb3" value="1"></td>
            <td><input type="text" name="nome[]" id="nome3"></td>
        </tr>
    </table>
    <input type="submit" value="enviar" name="enviar">
</form>

<?php
    if (isset($_POST['enviar'])) {
        var_dump($_POST['cb']);
        var_dump($_POST['nome']);
    }
?>

1 answer

0

The simplest way to interact with an array would be to use foreach, but in your case, it would be better to use a for because when finding a "checked" item, we take the name value with the same index.

It would be something like that:

for ($i = 0; $i < count($_POST['cb']); $i++) {
   // verifica se está checado
   if(isset($_POST[$i]['cb']))  {
      // pega o nome de uma linha checada
      $nome = $_POST[$i]['nome']

      // aqui faz alguma coisa, como inserir ou atualizar no banco
   }
}
  • I tried that way and it didn’t work. Thus the code: $name = array(); for ($i = 0; $i < Count($_POST['cb']); $i++) { if(isset($_POST['cb'][$i])) { $name[]= $_POST['name'][$i]; } } var_dump($name);

Browser other questions tagged

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