Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php - testing if a radio button is selected and get the value

Tags:

php

I'm using php. I'd like to know how can I test if a radio button is selected and get the value? i can test if the radio button is selected but i cannot get the value. I created a button to test this in my form. First I select a radio button, then i click on the button and it must display a message that says which value i selected and put this value into a variable. In order to test if a radio button is selected i did like this:

$selected_radio=$_POST['SINGLE_' . $question->id . $multi_name_adjust . ''];
if ($selected_radio = 'checked'){}

Thanks

like image 718
user1073001 Avatar asked Dec 07 '11 13:12

user1073001


People also ask

How do I get the value of a radio button in PHP?

To get selected value of a radio button: php if (isset($_POST['submit'])) { if(isset($_POST['radio'])) { echo "You have selected :". $_POST['radio']; // Displaying Selected Value } ?>

How do you check if a radio button has been selected?

Using Input Radio checked property: The Input Radio checked property is used to return the checked status of an Input Radio Button. Use document. getElementById('id'). checked method to check whether the element with selected id is check or not.

How do you check radio button is checked or not PHP?

It has been many years since I even looked at any PHP but if I recall correctly, you can just check $_POST["NAME_OF_RADIOBUTTON"]. if the radio button is selected, the value should be present, if it's not selected, the value in $_POST["NAME_OF_RADIOBUTTON"] will be null.


1 Answers

It's pretty simple, take a look at the code below:

The form:

<form action="result.php" method="post">
  Answer 1 <input type="radio" name="ans" value="ans1" /><br />
  Answer 2 <input type="radio" name="ans" value="ans2"  /><br />
  Answer 3 <input type="radio" name="ans" value="ans3"  /><br />
  Answer 4 <input type="radio" name="ans" value="ans4"  /><br />
  <input type="submit" value="submit" />
</form>

PHP code:

<?php 

$answer = $_POST['ans'];  
if ($answer == "ans1") {          
    echo 'Correct';      
}
else {
    echo 'Incorrect';
}          
?>
like image 159
Stefan Koenen Avatar answered Sep 24 '22 00:09

Stefan Koenen