Send PHP checkbox value

Asked

Viewed 1,130 times

2

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

For example, I want to take the checkbox value checked and do a validation, but it’s not getting 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';
}

?>

2 answers

3


Below is how your code should look, knowing your needs what seems most convenient to me would be to put them in an array, so I joined the answer of Diego with mine, getting:

<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;
};
}

?>
  • I just posted a piece of code, and yes I am using form and method= post. I cannot use radio due to functions of my application...

  • I get it, but you can use the checkbox normally, I don’t see problems, but what’s your goal for example, if the user clicks on both parties and gives a Ubmit? Just so you understand.

  • When the user fills in all fields, I need to take the checkbox value and make a comparison, if the checkbox marked has value="2000" then what will be written in the email will be Party 2

  • I understood, I changed the code, as the alternative is an array, I joined my code with @Diego’s. See if this is how I wanted it.

3

Try to do it this way:

  • In HTML change the name to an array:

    name='tipoFesta[]'

  • NO PHP handle array to ignore any blank fields:

    array_filter($_POST['tipoFesta']);

  • Make a foreach and within it do the validation:

    foreach ($tipoFesta_in as $key => $tipoFesta) {  
          // FAÇA AS> VALIDAÇÕES USANDO $tipoFesta[$key]    
     }
    
  • what would that $key be?

  • It is the 'step' of the array. It has the amount of fields with that name in html.

Browser other questions tagged

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