【问题标题】:Radio button checked text box required in PHPPHP中需要单选按钮选中的文本框
【发布时间】:2013-04-24 21:19:45
【问题描述】:

我对 PHP 很陌生,但学习很困难。我为我的学校网站创建了一个提交表单,在表单中我有一组单选按钮。见下文:

*Account Fund: <input type="radio" name="accfnd" value="nonprofit" <?php 
echo $nonprofitChecked; ?>>

Academic/Non-Profit <input type="radio" 
name="accfnd" value="commercial" <?php echo $commercialChecked; ?>>

Commercial <input type="radio" name="accfnd" value="uc" <?php echo $ucChecked; ?>>

UC  <input type="text" size="40" name="ucfund" 
value="<?php if(isset($_POST['ucfund'])) echo $_POST['ucfund'];?>" />
<?php if($ucfundError != '') { ?>
    <span class="error">
    <?=$ucfundError;?>
    </span>
<?php } ?>

选中value="uc"的单选按钮时,需要填写旁边的文本框,否则会收到错误消息。在大多数情况下,这工作正常,我遇到的问题是即使我检查了其他单选按钮之一,我也会收到要求填写文本消息的错误消息。只有在选中 uc 单选按钮时才需要文本框。我希望我说得通。

以下是 php 代码。我将不胜感激任何帮助。谢谢。

$accfnd = $_POST['accfnd']; 

if (isset($_GET['uc'])){  
    if ($_GET['accfnd'] == 'uc'){ $ucChecked = ' checked="checked" '; }  
} else if (trim($_POST['ucfund']) === '') { 
    $ucfundError = '<span class="error">Account fund is required for UCI users.</span>'; 
    $hasError = true; 
} else { 
    $ucfund = trim($_POST['ucfund']); 
}  

$body = " Account Fund: $accfnd \n\n UCI Account Fund: $ucfund";  

【问题讨论】:

  • 您是如何提交数据的?我看不到表格。你是通过 GET 还是 POST 发送的?

标签: php radio-button


【解决方案1】:

我没有看到名称为 uc 的表单元素;您的代码也可以简化为

$accfnd = isset($_POST['accfnd']) ? $_POST['accfnd'] : '';
$ucfund = isset($_POST['ucfund']) ? $_POST['ucfund'] : '';

if ($accfnd == 'uc') {
    $ucChecked = ' checked="checked" '; 

    if (trim($ucfund) == '') {
        $ucfundError = '<span class="error">Account fund is required for UCI users.</span>'; 
        $hasError = true; 
    }
}

$body = " Account Fund: $accfnd \n\n UCI Account Fund: $ucfund";  

【讨论】:

  • 哇!非常感谢大家的有用回复。我现在明白我做错了什么。何塞,我正在通过电子邮件发送数据,但我不明白 $_GET 或 $_POST 之间的区别,所以我想我只是同时使用了两者。但我想我现在将按照 Set Sail 的建议使用 $_REQUEST。再次感谢!!
【解决方案2】:

正如 Jose 所暗示的,您可以互换使用 $_GET 和 $_POST 表单数据变量。

最好的解决方案是在您可能使用$_GET[]$_POST[] 的任何地方使用$_REQUEST[]$_REQUEST 是一个合并的超全局变量,包含所有提交的表单数据,无论是 POST 还是 GET。它本质上是 $_GET 和 $_POST 的组合(以及 $_COOKIE)。更多信息/澄清here in the manual

其次,您问的问题是比较数据。您有多个从未执行过的嵌套 if() 和 elseif() 语句,因为 $_GET['uc'] 不存在。

$accfnd = $_REQUEST['accfnd']; 

if ( $accfnd == 'uc'){  // Commercial selected, text box required
    $ucChecked = ' checked="checked" ';
    if (trim($_REQUEST['ucfund']) === '') { 
        $ucfundError = '<span class="error">Account fund is required for UCI users.</span>'; 
        $hasError = true; 
    }
} else { 
    $ucfund = trim($_REQUEST['ucfund']); 
}  

$body = " Account Fund: $accfnd \n\n UCI Account Fund: $ucfund";  

【讨论】:

    猜你喜欢
    • 2021-06-02
    • 2023-03-28
    • 2012-09-19
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多