pTutorial

New way to learn PHP

PHP 5 radio button and check box

Get value from check box

In this section, we will get value from radio button and check boxes and also validate these two.

Difference between check box and radio button

Before getting value from check boxes you need to understand the difference between radio buttons and check boxes, in case of a radio button you can take one value only but in case of check boxes you can take multiple values.

Html for check box


<html
<body>
<form action="process.php" method="post">
<input type="checkbox" name="data[]" value="Audi">Audi<br/>
<input type="checkbox" name="data[]" value="Fiat">Fiat<br/>
<input type="checkbox" name="data[]" value="Bmw">Bmw<br/>
<input type="checkbox" name="data[]" value="Renault">Renault<br/>
<input type="submit" name="submit" value="Submit"/>
</form>
</body>
</html>

Get value from checkbox

<?php

/*process.php*/
if(@isset($_POST['submit']))
{
foreach($_POST['data'] as $selected)
{
echo $selected."
"; } } ?>

See the Html code above, it is a simple HTML form with four check boxes. We save this file form.html and send the data to the process.php with the help of the POST method.

Get value from radio button is easy task but to get value from check boxes is little bit difficult. With the help of array and for each loop you can get value from check boxes as shown above.

Note: You can also keep both file data into a single PHP file.

Validate check box

<?php

if(isset($_POST['submit']))
{
if(empty($_POST['data']))
{
echo "Select at least one";
}
else
{
foreach($_POST['data'] as $selected){
echo $selected."
"; } } ?>

You can validate checkboxes according to your condition like must be selected one or two as per your requirement. In the above example, validate with one mandatory select.

HTML for radio button

<html>
<body>
<form name="info"  method= "post" action= "" >
Male<input type="radio" name="n" value="male">
Female<input type="radio" name="n" value="female">
<input type="submit" name="S">
</form>
</body>
</html>

Radio button validation

<?php

if(isset($_POST['S']))
{
$name1=@trim($_POST['n']);
 
if($name1=="" ) 
{
echo "Select first";
}
else
{
echo "Correct
"; echo "You have selected :$name1"; } } ?>

You can simply validate radio button with the help of empty function and without empty function like check boxes.


QUOTES OF THE DAY

Each day provides its own gifts.

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER