PHP Form CheckBox

In this chapter you will learn:

  1. What is a checkbox
  2. Example - PHP Form CheckBox

Description

A checkbox field is a simple toggle button. It can be either on or off.

The value attribute should contain the value that will be sent to the server when the checkbox is selected. If the checkbox isn't selected, nothing is sent.


<label for="checkboxField">A checkbox field</label> 
<input type="checkbox" name="checkboxField" id="checkboxField" value="yes" /> 

You can preselect a checkbox by adding the attribute checked="checked" to the input tag:


<input type="checkbox" checked="checked" ... />. 

By creating multiple checkbox fields with the same name attribute, you can allow the user to select multiple values for the same field.

Example

The following script is for index.htm. It has several checkboxes.


<html>//from   j av a2 s  .  c om
<body>
<form action ="index.php">

<ul>
  <li><input type ="checkbox" name ="chkFries" value ="11.00">Fries</li>
  <li><input type ="checkbox" name ="chkSoda"  value ="12.85">Soda</li>
  <li><input type ="checkbox" name ="chkShake" value ="1.30">Shake</li>
  <li><input type ="checkbox" name ="chkKetchup" value =".05">Ketchup</li>
</ul>
<input type ="submit">
</form>

</body>
</html>

The following code is for index.php and it accepts the value from the checkboxes.


<?PHP/*java2 s  .c  om*/
print "chkFries:" .  $chkFries . "<br/>";
print "chkSoda:" $chkSoda . "<br/>";
print "chkShake:" . $chkShake . "<br/>";
print "chkKetchup" . $chkKetchup . "<br/>";

$total = 0;

if (!empty($chkFries)){
  print ("You chose Fries <br>");
  $total = $total + $chkFries;
}

if (!empty($chkSoda)){
  print ("You chose Soda <br>");
  $total = $total + $chkSoda;
}

if (!empty($chkShake)){
  print ("You chose Shake <br>");
  $total = $total + $chkShake;
}

if (!empty($chkKetchup)){
  print ("You chose Ketchup <br>");
  $total = $total + $chkKetchup;
}

print "The total cost is \$$total";

?>

Next chapter...

What you will learn in the next chapter:

  1. Form Select as Pull-down menu
  2. Form Select as List Box
  3. Form Select as multi-select list box
  4. Example - Form Select
Home » PHP Tutorial » PHP Form
PHP HTML Forms
PHP GET and POST
PHP Form Elements
PHP Form TextField
PHP Form Password Field
PHP Form Textarea
PHP Form CheckBox
PHP Form Select
PHP Form RadioButton
PHP Form Submit
PHP Form Reset
PHP Form Push Button
PHP Form Image
PHP Form Hidden Field
PHP Split Form Across Pages
PHP Form Validation
PHP Form File Upload
PHP Form Demo
PHP Form Empty Fields
PHP Form Multi-Value Fields
PHP Redirect after a Form Submission