Jump to content
Larry Ullman's Book Forums

Echoing Information From A Checkbox Into A Form


Recommended Posts

Here's what I'm trying to do:

 

I have a form with a checkbox group containing four checkboxes. The "name" for each checkbox is name="storetype[]". The values for the four checkboxes are: fashion, jewelry, home and other. I am successfully collecting the information fine using this code:

 

if (!empty($_POST['storetype'])) {

$storetype = $_POST['storetype'];

} else {

$storetype = FALSE;

$errormessage .= '<p class="error">You forgot to answer what type of store you have!</p>';

}

 

What I'm trying to do now is echo the information back into the form in case they forgot to fill out a different area of the form and get an error message saying so. I don't want them to have to recheck these boxes, but have them already checked for them if they checked them the first time.

 

I'm using this code:

 

 

<input type="checkbox" name="storetype[]" value="fashion" id="fashion" <?php if (!(strcmp("fashion", "$storetype"))) {echo "checked=\"checked\"";} ?> /><label for="fashion"> Fashion Boutique</label>

 

But, alas, it's not working. The boxes don't get checked.

 

Any help or direction as to what I'm doing wrong would be greatly appreciated.

 

Thanks!

Link to comment
Share on other sites

If the name of the form element is storetype[], then $_POST['storetype'] will be an array not a string. In this code here:

$storetype = $_POST['storetype'];

you're losing all the data the user selected anyway, so you need to fix that.

In the HTML form, to make it sticky, you need to check if $_POST['storetype'] (or a local variable) is set and, if so, if the value in question, such as "fashion", is found within the array.

Link to comment
Share on other sites

In case this can be of any help (I used to make this mistake): remember that every time you collect several answers, from checkboxes or from a multiple-select dropdown menu, for instance, what you (should) get is an array. So you must use a foreach loop (not an "if" conditional) to get the results, and to check the boxes if you want to make them sticky.

Link to comment
Share on other sites

  • 3 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

×
×
  • Create New...