简体   繁体   中英

PHP code for checkboxes for an HTML email form

I am using a tutorial for an HTML/PHP email form, it does validation and what not and showcases text fields and select fields, it however does not show checkboxes.

Here is the URL to the tutorial http://net.tutsplus.com/tutorials/html-css-techniques/build-a-neat-html5-powered-contact-form/

The text field code looks like such

<input type="text" id="phone" name="phone" value="<?php echo ($sr && !$cf['form_ok']) ? $cf['posted_form_data']['phone'] : '' ?>" placeholder="555-555-5555" />

The select looks like such

<option value="Select a size" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['size'] == 'Select a size') ? "selected='selected'" : '' ?>>Select a size</option>

What I am trying to figure out how to get the above to be proper syntax when using checkboxes. Here is my attempt

<input type="checkbox" id="color" name="color" value="<?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['red'] : '' ?>" />

It is improper syntax. Mind you I am going to have multiple checkboxes and 1 or all might need to be shown in the recipient email. Can someone please assist that would be awesome.

If I am correct you are trying to set the checked state. You are doing this in the value attribute, which is incorrect. Assuming this is the checkbox for the color red something like this should be the syntax:

<input type="checkbox" 
       id="color" 
       name="color" 
       value="red"
       <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['red']) 
                  ? 'checked="checked"'
                  : ''; ?> 
       />

An example of the ternary operation:

// Like asking php a question
(TRUE) ? 'this is true' : 'this is false';
--> 'this is true'

Broken down into a regular if/else statement:

if(TRUE)
{
    echo 'this is true';
}
else
{
    echo 'this is false';
}
--> 'this is true'

Your ternary operator syntax is not correct for the checkboxes:

($sr && !$cf['form_ok'] && $cf['posted_form_data']['red'] : ''

You're missing the ? part and never close the parentheses. This will result in a syntax error.

These lines had problems, as well....

<input type="text" id="phone" name="phone" value="<?php echo ($sr && !$cf['form_ok'] ? $cf['posted_form_data']['phone'] : '');?>" placeholder="555-555-5555" />
<option value="Select a size" <?php echo ($sr && !$cf['form_ok'] && $cf['posted_form_data']['size'] == 'Select a size' ? "selected='selected'" : '');?>>Select a size</option>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM