user2953877
user2953877

Reputation: 43

keeping radio button checked in PHP?

I have a real hard time keeping radio buttons checked after submitting a form!

this question has been asked several times and I did follow some instruction and finally got one of the radio buttons checked after submitting the form. but it doesn't work for the second radio button!

This is my PHP code:

<?php
$postRadioName = '';
if (isset($_POST['ship']) || '7' == $_POST['ship']) {
    $postRadioName = ' checked="checked"';
}else{

    if (isset($_POST['ship']) || '12' == $_POST['ship']) {
    $postRadioName = ' checked="checked"';
    }

}
?>

and this is my form :

<form id="radios" name="radios" method="post" action="order.php" enctype="multipart/form-data">
<p>
<label>UK Shipping £7 </label>
    <input type="radio" name="ship" value="7"<?php echo $postRadioName;?>  onclick="this.form.submit()">
    </p>
    <p>
<label>International Shipping £12</label>
    <input type="radio" name="ship" value="12"<?php echo $postRadioName;?> onclick="this.form.submit()">
    </p>
</form>

what am I doing wrong here?

Upvotes: 0

Views: 956

Answers (2)

Flash Thunder
Flash Thunder

Reputation: 12036

First of all... you are using || in if functions... that basically means OR. And it should be &&, that means AND ...

if (isset($_POST['ship']) || '7' == $_POST['ship']) means... if $_POST['ship'] is defined or has value of 7... has no sense... will always return true, as far as any option is selected, won't even check the value of 7, because when using || it checks the fist condition, and if it's true, doesn't even check the second one.

Second thing... $postRadioName = ' checked="checked"'; just leave $postRadioName = ' checked'; - checked attribute doesn't have value. It simply is or is not. Same thing with selected.

Upvotes: 1

Alireza Fallah
Alireza Fallah

Reputation: 4607

Change the code to :

PHP :

<?php
$postRadioName = '';
if ('7' == $_POST['ship']) {
    $postRadioName7 = ' checked="checked"';
}else{

    if ('12' == $_POST['ship']) {
    $postRadioName12 = ' checked="checked"';
    }

}
?>

HTML :

<form id="radios" name="radios" method="post" action="order.php" enctype="multipart/form-data">
<p>
<label>UK Shipping £7 </label>
    <input type="radio" name="ship" value="7"<?php echo $postRadioName7;?>  onclick="this.form.submit()">
    </p>
    <p>
<label>International Shipping £12</label>
    <input type="radio" name="ship" value="12"<?php echo $postRadioName12;?> onclick="this.form.submit()">
    </p>
</form>

by putting || between isset($_POST['ship']) and '7' == $_POST['ship'], if $_POST['ship'] exists, the if condition will return true, and the else part does not executes (even if $_POST['ship']==12 ).

Upvotes: 2

Related Questions