Jump to content

Problem with radio buttons in form


maciek4

Recommended Posts

I have a form where I have a field with 4 radio buttons containing options:

A
B
C
D

The field is required so if no option is selected then an error message appears in red color. When the user selects one option and clicks submit I want it to be sent by mail to my account.

[code]$progress = array();
$progress_error = false;

if(!isset($progress) || !is_array($progress) || empty($progress)) {
        $progress_error = true;
        $error = true;
    }

if(!$error) {
$mailBody .= "Rate your progress:\n";
        if(isset($progress['A'])) $mailBody .= "- A\n";
        if(isset($progress['B'])) $mailBody .= "- B\n";
        if(isset($progress['C'])) $mailBody .= "- C\n";
        if(isset($progress['D'])) $mailBody .= "- D\n";

<INPUT TYPE="radio" NAME="progress" value="A" <?echo isset($progress['A']) ? 'checked' : ''; ?>>&nbsp;A <br>
<INPUT TYPE="radio" NAME="progress" value="B" <? echo isset($progress['B']) ? 'checked' : ''; ?>>&nbsp;B<br>
<INPUT TYPE="radio" NAME="progress" value="C" <? echo isset($progress['C']) ? 'checked' : ''; ?>>&nbsp;C<br>
<INPUT TYPE="radio" NAME="progress" value="D" <? echo isset($progress['D']) ? 'checked' : ''; ?>>&nbsp;D<br>
[/code]

The problem is that all those options have the same name="progress" so an error message appears. If I give unique names to each option then it works fine but then the user can select all the options altogether A,B,C,D and I only want him to select one of these options. How can I fix it? :(
Link to comment
https://forums.phpfreaks.com/topic/9304-problem-with-radio-buttons-in-form/
Share on other sites

No, the problem is not that they all have the same name, the problem is that you are referencing the name incorrectly. Try this:
[code]<?php
$progress_error = false;

if(!isset($_POST['progress'])  || empty($_POST['progress'])) {
        $progress_error = true;
        $error = true;
    }
else {
        $mailBody .= "Rate your progress:\n";
        $mailBody .= '- ' . $_POST['progress'] . "\n"; }
?>
<INPUT TYPE="radio" NAME="progress" value="A" <?echo ($_POST['progress'] == 'A') ? 'checked' : ''; ?>> A <br>
<INPUT TYPE="radio" NAME="progress" value="B" <? echo ($_POST['progress'] == 'B') ? 'checked' : ''; ?>> B<br>
<INPUT TYPE="radio" NAME="progress" value="C" <? echo ($_POST['progress'] == 'C') ? 'checked' : ''; ?>> C<br>
<INPUT TYPE="radio" NAME="progress" value="D" <? echo ($_POST['progress'] == 'D') ? 'checked' : ''; ?>> D<br>
[/code]
In a radio button the name is not a array and can only have one value.

Ken

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.