Chris
Chris

Reputation: 1654

Using the radio button 'checked' value in HTML and PHP

So, I have a questions regarding the input type radio in HTML. As you know, you can put checked as a value, this will mark it as checked.

The story is I am getting a 0 or 1 value from my database. I am then checking if it's 0 or 1 and will then mark one of the radio button's as checked.

My code is as follows:

<?php if($pay_op == 0) { ?>

<input type="radio" value="paypal" id="pay_op" checked>PayPal<br />
<input type="radio" value="other" id="other_op">Other<br/>
<input type="submit" id="pay_op_submit" />

<?php } elseif ($pay_op == 1) { ?>

<input type="radio" value="paypal" id="pay_op">PayPal<br />
<input type="radio" value="other" id="other_op" checked>Other<br/>
<input type="submit" id="pay_op_submit" />
<?php } ?>

My problem now is, whenever I try to mark the other radio button as checked by clicking on it, both radio buttons are checked?

I thought that this might have something to do with me checking if the value returned from the database is 0 or 1 and it will keep one of the radio buttons checked until that value is changed. Now my question is, does anyone know a solution to this issue so that whenever someone clicks on something different than the default checked radio button it will actually check that one and not both of them?

Any tips are highly appreciated! =)

Thanks!

Upvotes: 3

Views: 3945

Answers (1)

Fluffeh
Fluffeh

Reputation: 33502

Radio buttons work basically as a named group. The browser only un-checks a radio button if it is linked to the other radio buttons with a property called name.

<?php 
    if($pay_op == 0) 
    { ?>
        <input name ="myGroup" type="radio" value="paypal" id="pay_op" checked>PayPal<br />
        <input name ="myGroup" type="radio" value="other" id="other_op">Other<br/>
        <input name ="myGroup" type="submit" id="pay_op_submit" />
    <?php 
    } 
    elseif($pay_op == 1) 
    { ?>
        <input name ="myGroup" type="radio" value="paypal" id="pay_op">PayPal<br />
        <input name ="myGroup" type="radio" value="other" id="other_op" checked>Other<br/>
        <input name ="myGroup" type="submit" id="pay_op_submit" />
    <?php 
    } 
?>

Upvotes: 3

Related Questions