drduh44480 2015-02-19 02:31
浏览 31
已采纳

检查提交单选按钮 - PHP

I need to check a radio button input on submit.

If none of the radio buttons are checked, $err1_diet gets set to true and the red class needs to be added.

And I also need to know which radio button was checked since this isn't the only question in the form.

  if( !isset($_POST['diet']) ){
    $err1_diet = true;
  }elseif($_POST['diet'] == 1){
    $diet = true;
  }else{
    $diet = false;
    $yes = true;
  }

<p class="<?php echo (($err1_diet == true) ? "red" : "" ); ?>">&#8226; Are you on a diet?<?php var_dump($err1_diet); ?></p>
<input type="radio" name="diet" value="1" <?php echo (($diet) ? 'checked="true"' : "" ); ?> /> Yes
<input type="radio" name="diet" value="0" <?php echo (($diet) ? '' : 'checked="true"' ); ?> /> No
  • 写回答

1条回答 默认 最新

  • dpl74687 2015-02-19 15:53
    关注

    Actually no ... it's checking one of the radio buttons before the form is submitted. That's the problem

    You can solve your problem using $_SERVER['REQUEST_METHOD']=='POST' for example:

    if( $_SERVER['REQUEST_METHOD']=='POST' and !isset($_POST['diet']) ){
        $err1_diet = true;
      }elseif($_POST['diet'] == 1){
        $diet = true;
      }else{
        $diet = false;
        $yes = true;
      }
    
    <p class="<?php echo (($err1_diet == true) ? "red" : "" ); ?>">&#8226; Are you on a diet?<?php var_dump($err1_diet); ?></p>
    <input type="radio" name="diet" value="1" <?php echo (($diet) ? 'checked="true"' : "" ); ?> /> Yes
    <input type="radio" name="diet" value="0" <?php echo (($diet) ? '' : 'checked="true"' ); ?> /> No
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度