Link to home
Start Free TrialLog in
Avatar of karimjohnson
karimjohnson

asked on

using php to set form values

I have a php file that includes a form with checkboxes and other fields. I need a way to use php to check the boxes based on variables. I do this with lists using the following:

<option value="Houses" <?php if ($buildingtype=="Houses") echo "selected";?>Houses</option>

I need something equivalent for checkboxes. Here is what I have tried (and what does not work):

<input name="Sales" type="checkbox" value="Yes" <?php if ($sales=="Yes") echo "checked";?>>Sales
ASKER CERTIFIED SOLUTION
Avatar of Steve Bink
Steve Bink
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
since you are not dealing with any variables in your string PHP is actually faster if you do the following:
<input name="Sales" type="checkbox" value="Yes"<?php if ($sales=="Yes") echo ' checked="checked"'; ?> />Sales

Only outputting 'checked' doesn't make the form get checked.  You need checked="checked" to make it work.

The best way to make this work is to actually create a simple class that handles outputting all of your form elements.  This way you can simply call a static method in the class to output your checkbox.  This method is a lot easier to work with and less hassle overall.
Class HTML {
 
     public static function checkbox($name, $value, $checked = false, $extra) {
         // Here you build the output of the form field you need.
     }
}

Open in new window