检查哪个单选按钮?

时间:2011-08-17 00:51:46

标签: php html

我想检查哪个单选按钮被选中。然后,在我问这个问题之前,我查看了这里的问题,他们说代码

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

就是答案。但是,我收到错误“使用未定义的常量文档 - 假定'文档'”和

Call to undefined function getElementById().

哪里出错了?我是否必须编写getElementById('number1').checked的函数,因为它说“未定义”? 感谢

3 个答案:

答案 0 :(得分:8)

您的代码是Javascript。要检查PHP中单选按钮的值,它需要具有name属性,该属性是通过GET或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'];
}

答案 1 :(得分:3)

您发布的代码是JavaScript。为了确定是将一个表单作为帖子提交,还是使用superglobals $ _POST [],$ _GET [],$ _REQUEST []来获取和查询该值。

您有HTML代码:

<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 />

假设您使用post方法将表单提交到您的php文件,以下代码将测试选择了哪个单选按钮。

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

答案 2 :(得分:1)

您想知道单选按钮是否已被检查?在客户端浏览器中?还是在服务器上?

如果要查看客户端,请使用javascript的

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

如果要查看服务器,请使用Michael的PHP