user2979139
user2979139

Reputation: 163

PHP radio button check issue

No matter which radio button is checked then submitted, no is always shown.

HTML:

<input type="radio" id="formyes" name="checkyn" value="yes"/>
<label for="formyes">yes</label>
<input type="radio" id="formno" name="checkyn" value="no"/>
<label for="formno">no</label>

PHP var dump of $_POST:

'checkyn' => string 'no' (length=2)

How can I test if yes is selected if when yes is selected no is always logged?

Upvotes: 1

Views: 181

Answers (4)

pon aravind
pon aravind

Reputation: 5

Your HTML should be

<input type="radio" id="formyes" name="checkyn[]" value="yes"/>
<label for="formyes">yes</label>
<input type="radio" id="formno" name="checkyn[]" value="no"/>
<label for="formno">no</label>

ADD [ ] after checkyn in HTML this will denote array in PHP

<?php
if ($_SERVER['REQUEST_METHOD']=='POST'){
    $check = $_POST['checkyn'][0];
}
?>

if you echo $check; checked button value will return

Upvotes: 0

Andreea
Andreea

Reputation: 139

Try this:

if($_POST){
print_r($_POST['checkyn']);
}

Upvotes: 0

Awlad Liton
Awlad Liton

Reputation: 9351

You have two button with same name it means that you can select one at a time. if you select one then another will be unselect. I think you are saying that $_POST['checkyn'] is always give you no. if that the case you should select one by default in your html:

<input type="radio" id="formyes" name="checkyn" value="yes" checked/>
<label for="formyes">yes</label>
<input type="radio" id="formno" name="checkyn" value="no"/>
<label for="formno">no</label>

you can get is value like this:

  if(isset($_POST['checkyn']) )
    if( $_POST['checkyn'] == 'yes'){

    //yes selected do your stuff
    }
    else{

    //no selected
    }
}

Upvotes: 0

Lal krishnan S L
Lal krishnan S L

Reputation: 1745

Try this

if($_POST['checkyn']=='yes')
{
    echo "Yes checked";
}elseif($_POST['checkyn']=='no')
{
   echo "No checked";
}

Upvotes: 1

Related Questions