1

Hello I am creating a HTML + PHP email form. My form and function is working perfectly aside from my checkboxes. I have two checkboxes.

<input type="checkbox" id="boxfan" name="boxfan[]"/>
<label for="boxfan">A fan?</label>

<input type="checkbox" id="boxgbps" name="boxfan[]"/>
<label for="boxalbum">Bought an album?</label>

I want the value to be send as Yes or No, send Yes if the checked and No if unchecked.

For example:

A fan? Yes

Bought an album? No

Any, suggestion is appreciated. Thanks.

My actual form is here It's in Danish that's why I just used a simple example.

4
  • 4
    $yn = (isset($_POST['boxfan'][$i])) ? 'Yes' : 'No'. Since checkboxes aren't submitted unless they ARE checked, the mere presence of the checkbox's name in _POST means it was checked. Commented Jan 30, 2014 at 16:38
  • I'm not going to put in answer until I see what you have as far as PHP goes. Seeing what you've posted for code, you're (and as you already know) doing it incorrectly. Questions like these, (and I take this from experience), always tend to open up a "can of worms". There are too many ways to go about this. So far, Marc B's comment (+1) is a good method, using a ternary operator. Commented Jan 30, 2014 at 16:40
  • @MarcB is right. What he's suggested is a simple ternary that says if it's set (yes only checkbox), its yes. If it doesn't (exist), it's automatically no. 'Tis the only way (other than maybe a convoluted creation of an arbitrary "no" checkbox via JS) Commented Jan 30, 2014 at 16:45
  • 1
    Thanks you guys, looks like you are right, so I'll just use a condition then. Thanks, appreciated. Commented Jan 30, 2014 at 16:53

2 Answers 2

3

If you want to send each in a seperate email:

foreach($_POST['boxfan'] as $boxfan){
    if(isset($boxfan)){
        $message = "Yes";
        mail($to, $subject, $message);
    } else{
        $message = "No";
        mail($to, $subject, $message);
    }
}

But if you want to send both in one email:

$message = null;
foreach($_POST['boxfan'] as $boxfan){
    if(isset($boxfan)){
        $message .= "Yes\r\n";
    } else{
        $message .= "No\r\n";
    }
}
mail($to, $subject, $message);
Sign up to request clarification or add additional context in comments.

1 Comment

this is interesting, I'll try this one.
0

This is how Rails does it:

<input type="hidden" name="boxfan" value="No"/>
<input type="checkbox" id="boxgbps" name="boxfan" value="Yes"/>

[EDIT] but you won't be able to make it an array variable then.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.