0
Thanks

A few words of thanks would be greatly appreciated.

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>


Thanks to holow1 for this tip.
0
Thanks

A few words of thanks would be greatly appreciated.

Ask a question
CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jean-François Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.
This document, titled « PHP - Creating a checkbox with limited choices », is available under the Creative Commons license. Any copy, reuse, or modification of the content should be sufficiently credited to CCM (ccm.net).

Subscribe To Our Newsletter!

The Best of CCM in Your Inbox

Subscribe To Our Newsletter!