0

所以我制作了一个注册表单,用户必须在继续之前选择三个单选选项之一。但是,如果用户没有选择选项并单击提交,我想至少显示一条消息,上面写着“请选择一个选项”或其他内容。到目前为止,这是我的代码:

<?php
$reg_type = "";
function setclick()
{
    if(isset($_POST["Submit"]))
        $clicked=1;
    else 
        $clicked=0;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["Reg_type"])) {
        $clicked=1;
        header('Location: Registration_1.php');
    }
    else {
        $reg_type = $_POST["Reg_type"];
        header('Location: Registration_2.php');
    }
}
echo $clicked;
?>

<form name="frmtype" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST" >
<input type="radio" name="Reg_type" value="1"/> Registering myself with credit card or bank account <br/>
<input type="radio" name="Reg_type" value="2"/> Registering multiple people using credit card or bank account <br/>
<input type="radio" name="Reg_type" value="3"/> Registering multiple people using a purchase order <br/>
<input type="submit" name="Submit" value="Submit" />
<?php 
setclick();
if($clicked)
    echo "Please select an option";
?>

如果他们没有选择选项并单击提交,我真的很难让逻辑下降以显示错误消息。

4

3 回答 3

1

如果表单已发布,您的setclick()函数将始终设置为 true。$clicked由于您随后setclick()在主 php 块之后调用,因此其余逻辑是否已更改它都是正确的。尝试这个:

 if(isset($_POST['Reg_type']) && $_POST['Reg_type'] != ''){ 
    $reg_type = $_POST['Reg_type'];
    header('Location: Registration_2.php');
 } else $clicked = true;

然后在表单下方的页面底部:

 if($clicked) echo "Please select an option";
于 2012-09-09T03:53:15.940 回答
0

尝试这个

<script>
    function checkform(){

    var checked = false;
    var buttons = document.getElementsByTagName('input')
    for (var i = 0; i < buttons.length ; i++) {
       if (buttons[i].checked) {
           checked = true;
           break;
       }
   }
   return checked;

   }
</script>

<form onsubmit="return checkform()">
<input type="radio" name="Reg_type" value="1"/> Registering myself with credit card or bank account <br/>
<input type="radio" name="Reg_type" value="2"/> Registering multiple people using credit card or bank account <br/>
<input type="radio" name="Reg_type" value="3"/> Registering multiple people using a purchase order <br/>
<input type="submit" name="Submit" value="Submit" />

检查小提琴

这应该让你开始。请注意,此脚本通过标签名称选择元素,这意味着它将获取表单中的任何输入。如果您可以使用jQuery,我强烈推荐它,它将使此类任务变得微不足道。

于 2012-09-09T03:46:42.747 回答
0
<?php
 $reg_type = $_POST['Reg_type'];

 if($reg_type == "1"){
       //action 1
 } else if($reg_type == "2"){
      //action 2 
 } else if($reg_type == "3") {
     //action 3 
 } else {
    // no radio button is checked. display the message

    $message = "Please select an option";
 }

?>
于 2012-09-09T03:50:48.313 回答