user893970
user893970

Reputation: 899

which radio button is checked?

I wanted to check which radio button is checked. Then, I looked at the questions in here before i asked this question and they said that the code

        if(document.getElementById('number1').checked) 

is the answer. But, i got the error "Use of undefined constant document - assumed 'document'" and

Call to undefined function getElementById().

Where did it go wrong? Did i have to write the function of getElementById('number1').checked because it says "undefined"? Thanks

Upvotes: 6

Views: 27446

Answers (3)

Michael Berkowski
Michael Berkowski

Reputation: 270607

Your code is Javascript. To check the value of a radio button in PHP, it needs to have a name attribute, which was sent in a form either by a GET or POST.

// If form method='get'
if (isset($_GET['name_of_radio_group'])) {

  // Show the radio button value, i.e. which one was checked when the form was sent
  echo $_GET['name_of_radio_group'];
}

// If form method='post'
if (isset($_POST['name_of_radio_group'])) {

  // Show the radio button value, i.e. which one was checked when the form was sent
  echo $_POST['name_of_radio_group'];
}

Upvotes: 10

Steve Buzonas
Steve Buzonas

Reputation: 5700

The code you have posted is in JavaScript. In order to determine is to submit a form as a post or get and query the value with the superglobals $_POST[], $_GET[], $_REQUEST[].

You have your HTML code:

<input type="radio" name="radio_group1" value="rg1v1" />Radio Group 1 - Value 1<br />
<input type="radio" name="radio_group1" value="rg1v2" />Radio Group 1 - Value 2<br />
<input type="radio" name="radio_group1" value="rg1v3" />Radio Group 1 - Value 3<br />

Assuming that you submitted the form using the post method to your php file the following code will test for which radio button is selected.

<?php
    switch($_POST['radio_group1']) {
        case "rg1v1":
            $value = "Radio Group 1 - Value 1 has been selected.";
            break;
        case "rg1v2":
            $value = "Radio Group 1 - Value 2 has been selected.";
            break;
        case "rg1v3":
            $value = "Radio Group 1 - Value 3 has been selected.";
            break;
        default:
            $value = "No radio has been selected for Radio Group 1";
    }
?>

Upvotes: 5

Coomie
Coomie

Reputation: 4868

Where do you want to know if the radio button is checked? In the clients browser? Or on the server?

If you want to check on the client, you use javascript's

if (document.getElementById('number1').checked)

If you want to check on the server, you use Michael's PHP

Upvotes: 1

Related Questions