检查单选按钮的第一个值(Codeigniter)

时间:2017-06-14 09:20:49

标签: php codeigniter radio-button

我正在将数据从数据库填充到单选按钮,并希望检查第一个值为默认,但我不知道如何做到这一点。这是我到目前为止所做的编码。

查看

<?php if($designThemes != null){;  ?>

<?php foreach ($designThemes as $designTheme) { ?>

<?php
$designThemesValue = (set_value('theme_name') ? set_value('theme_name') : $designTheme['slug_url']);
$designThemesAttr = array(
    'name'  => 'designThemes',
    'value' => $designThemesValue,
);
?>
<div class="col-md-4 col-sm-4">
    <div class="radio custom-radio">
        <label>
            <?php echo form_radio($designThemesAttr); ?>
            <span class="fa fa-circle"></span> <?php echo $designTheme['theme_name'] ?>
        </label>
    </div>
</div>
<?php }}; ?>

如果我在'checked' => TRUE中添加$designThemesAttr = array(),系统会将单选按钮的最后一个值检查为默认值,但我想检查第一个值

2 个答案:

答案 0 :(得分:2)

解决了您的问题,您可以通过条件语句将其设置为替换您的代码

   <?php if($designThemes != null){;  ?>

<?php $i=1;foreach ($designThemes as $designTheme) { ?>

<?php
$designThemesValue = (set_value('theme_name') ? set_value('theme_name') : $designTheme['slug_url']);
$designThemesAttr = array(
    'name'  => 'designThemes',
    'value' => $designThemesValue,
);
if($i==1){
    $designThemesAttr['checked'] = TRUE;
}
?>
<div class="col-md-4 col-sm-4">
    <div class="radio custom-radio">
        <label>
            <?php echo form_radio($designThemesAttr); ?>
            <span class="fa fa-circle"></span> <?php echo $designTheme['theme_name'] ?>
        </label>
    </div>
</div>
<?php $i++; }}; ?>

答案 1 :(得分:0)

在$ designThemesAttr = array()中的

'checked' => TRUE系统将检查单选按钮的最后一个值作为默认值。这是正确的,因为你在for循环中执行它,并且在组内只保留一个无线电。所以最后一个显示已检查。

因此,维护一个变量来计算迭代次数,如:

$ count = 1;

if( $count = 1; )
{
   // use 'checked' => TRUE here
   $count++;  // The value is incremented so that the if condition can't run again. This will add 'checked' => TRUE to first radio only.
}