Send PHP checkbox value

1

Can I use the same name="" in two inputs of type checkbox to do a validation in PHP?

For example, I want to get the value of the checked checkbox and do a validation, but it is not taking any value.

<input id="add-festa-k" onclick="marcaDesmarcaFesta(this)" class="tfesta" type="checkbox" name="tipoFesta" value="1499" />
<label for="add-festa-k">Festa 1</label>

<input id="add-festa-k" onclick="marcaDesmarcaFesta(this)" class="tfesta" type="checkbox" name="tipoFesta" value="2000" />
<label for="add-festa-k">Festa 2</label>


<?php

$tipoFesta = $_POST['tipoFesta'];

if($tipoFesta >= 2000){
    $tipoFesta = 'Festa 2';
}else{
    $tipoFesta = 'Festa 1';
}

?>
    
asked by anonymous 15.05.2018 / 15:46

2 answers

1

Here's how your code should look, knowing what you want is what would be most convenient to put in an array, so I've added the Diego with my, staying:

<form method="POST" action="">
<input id="add-festa-k" class="tfesta" type="checkbox" name="tipoFesta[]" value="1499" />
<label for="add-festa-k">Festa 1</label>
<input id="add-festa-k" class="tfesta" type="checkbox" name="tipoFesta[]" value="2000" />
<label for="add-festa-k">Festa 2</label>
<br>
<input type="submit" value="enviar">
</form>

<?php

$tipoFesta = array_filter($_POST['tipoFesta']);

foreach($tipoFesta as $key => $tipoFesta){
  if($tipoFesta == 2000){
      $tipoFesta = 'Festa 2 - Valor de R$2.000,00';
      echo "<br>". $tipoFesta;
}else{
  $tipoFesta = 'Festa 1 - Valor de R$1.499,00';
  echo "<br>". $tipoFesta;
};
}

?>
    
15.05.2018 / 16:16
1

Try doing the following:

  • In HTML, change the name to an array:

    name='tipoFesta[]'

  • In PHP, treat the array to ignore any blank fields:

    array_filter($_POST['tipoFesta']);

  • Make a foreach and inside it validate:

    foreach ($tipoFesta_in as $key => $tipoFesta) {  
          // FAÇA AS> VALIDAÇÕES USANDO $tipoFesta[$key]    
     }
    
15.05.2018 / 16:22