Ryan McKenna
Ryan McKenna

Reputation: 83

Radio buttons and IF statements

I have a form of radio buttons, I want some code to run that depends on which radio button is chosen. Originally I did this by making the "name" different for each choice, but it causes problems as the names of each radio button should be the same.

Here's a form code example

<li><label for="vsat">YES</label><input type="radio" name="camp" id="vsat" value="vsat" ></li>
<li><label for="vsat2">NO</label><input type="radio" name="camp" id="vsat2"     value="vsat2" ></li>

So there's two options, yes or no. I want it to echo "You chose YES" if yes is chosen and "You chose NO" if no is chosen.

Here's how I'm trying to do it

if(isset($_POST['vsat'])){
    echo "You chose YES";
}elseif(isset($_POST['vsat2'])){
    echo "You chose NO";
}

Make sense? I'm not even sure if it is possible the way I'm trying

Upvotes: 0

Views: 165

Answers (4)

Nikhil Vaghela
Nikhil Vaghela

Reputation: 222

this php code

 <?php
    if(isset($_POST['submit_btn'])){
    echo  $_POST['camp'];

    if($_POST['camp']=='vsat'){

    echo "You chose YES";

    }else{
    echo "You chose NO";

    }

}
?>

this is form

<form method="post" action="">
<li><label for="vsat">YES</label><input type="radio" name="camp" id="vsat" value="vsat" ></li>
<li><label for="vsat2">NO</label><input type="radio" name="camp" id="vsat2"     value="vsat2" ></li>
<li><input type="submit" name="submit_btn" /></li>
</form>

Upvotes: 1

mochalygin
mochalygin

Reputation: 742

I think you need change your code like this:

if ($_POST['camp'] == 'vsat') {
    echo "You chose YES";
}
elseif ($_POST['camp'] == 'vsat2') {
    echo "You chose NO";
}

Becouse the value you will check in radio-button-group will be sent to your PHP-script within variable $_POST['camp'] ('camp' is the name-parameter of radio-button). It will contain value 'vsat' or 'vsat2'.

Upvotes: 2

DerVO
DerVO

Reputation: 3679

The value of the selected radio button ('vsat' or 'vsat2') will be assigned to $_POST['camp'], while 'camp' is the name of the radio-buttons:

if (isset($_POST['camp']) && $_POST['camp']=='vsat') {
    echo "You chose YES";
} elseif (isset($_POST['camp']) && $_POST['camp']=='vsat2') {
    echo "You chose NO";
}

PS: the isset() is there to prevent a NOTICE popping up if none of the two radio buttons is checked. $_POST['camp'] will be undefined in this case.

Upvotes: 3

danmullen
danmullen

Reputation: 2510

You should be checking the value of the $_POST['camp'] variable:

if ($_POST['camp']) == 'vsat') {
    echo "You chose YES";
} elseif ($_POST['camp'] == 'vsat2') {
    echo "You chose NO";
}

The names of the variables are passed as $_POST variables when you submit the form, not the IDs.

Upvotes: 3

Related Questions