dongzhi9032
2011-07-21 07:04
浏览 189
已采纳

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

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-21 07: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>
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doushao5047 2011-07-21 07:15

    You should use javascript validation, intercepting commit and checking if some button is checked. But remember, that you have to validate also on server side, cause JS can be ommited.

    Or, if wide browser support is not your concern - HTML5 supports form constraints validation ( https://developer.mozilla.org/en/HTML/HTML5/Forms_in_HTML5 )

    评论
    解决 无用
    打赏 举报
  • dongwei6700 2011-07-21 07:35
    <input type="submit" value="Submit" name="B1" disabled="disabled">
    

    Above is an example of a Disabled submit button. You will have to use JavaScript to remove the disabled="disabled" attribute from the Submit button once user checks the checkboxes you want them to check.

    http://www.techchorus.net/disable-and-enable-input-elements-div-block-using-jquery

    There's a bit of a reading that should get you to understand the logic a lot better! :)

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题