Monday, 24 November 2014

PHP - Creating a checkbox with limited choices

I am currently creating a PHP form in which there are check boxes.
  • I want to know how to limit the number of response options. For example, if the user checks more than one box, an error message is displayed.


Here's how it look: 

<p>Choice</p>
<p>1 <input type="checkbox" name="reponse[]" value="1">
2 <input type="checkbox" name="reponse[]" value="2">
3 <input type="checkbox" name="reponse[]" value="3"></p>

<input type="submit" value="validate" name="ok"><br/>

<?php
 if (isset($_POST['ok']))
 {
                //empty message variable
  $msg = '';
  
  if(isset($_POST['reponse']))
  {
   echo '<p>Your choice : </p>';
   foreach ($_POST['reponse'] as $choix)
   {
    echo $choix.'<br/>';
   }
  }
  else
  {
   echo 'Please make a choice';
  }
 }
?>

Solution

<html>
<body>
<p>Choice</p>
<p>
<form method="POST" action="index.php">
1 <input type="checkbox" name="reponse[]" value="1">
2 <input type="checkbox" name="reponse[]" value="2">
3 <input type="checkbox" name="reponse[]" value="3"></p>

<input type="submit" value="validate" name="ok"><br/>
</form>

<?php

 if (isset($_POST['ok']))
 {
                //empty message variable
  $msg = '';
  
echo ("the number is ".count($_POST['reponse']));
  
  if(isset($_POST['reponse']))
  {
   echo '<p>Your choice : </p>';
   foreach ($_POST['reponse'] as $choix)
   {
    echo $choix.'<br/>';
   }
  }
  else
  {
   echo 'Please make a choice';
  }
 }
?>
</body>
</html>

0 comments:

Post a Comment