dongzhi9032 2011-07-20 23:04
浏览 190
已采纳

如果没有选中单选按钮,如何提交表单

I using PHP in order to create an HTML form.
The form has 3 radio buttons and a submit button.
In the initial state of the form, none of the radio buttons is checked.
I want to make the form not to be submitted if non of the radio buttons is checked.
Is there any way to do that? I attached part of the PHP code.

    for($i=0; $i<$nChoices; $i++) {
$Text='<input type="radio" name="answer" value="' . $IdChoices[$i] . '"';
$Text.=">  ". $Choices[$i] . "</input>";
$choiceoutput.= $Text."<br /><br />";
}

Thanks!

  • 写回答

3条回答 默认 最新

  • dseax40600 2011-07-20 23:22
    关注

    This javascript can be used for simple client-side validation. It's not considered safe to only validate on the client-side but if your purpose is to see if the user actually selected an value this will do. Otherwise further validation needs to be taking place in your php script.

    <script type="text/javascript">
    function validate()
    {
      var retval = false;
      for (var i=0; i < document.myForm.r.length; i++)
      {
        if (document.myForm.r[i].checked)
        {
          retval = true;
        }
      }  
    
      return retval;
    }
    </script>

    Simple form for putting it to work.

    <form name="myForm" action="page.php" onsubmit="return validate()" method="post">
    <input type="radio" id="r">
    <input type="radio" id="r">
    <input type="submit" value="ok">
    </form>
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部