开发者

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


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'];
}


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";
    }
?>


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜