如何在foreach循环中设置单选按钮?

时间:2013-11-15 17:58:50

标签: php jquery wordpress foreach radio-button

我正在Wordpress中创建一个自定义后端,其中一部分是能够从一个使用foreach循环自动更新的案例研究列表中进行选择,并在所选案例研究中插入一个链接。页。后端中的无线电列表使用以下代码

创建
        <?php 
            $checked = ' checked="checked"';
            $mypostype = get_posts(array(
                'post_type' => 'case_study',
                'showposts' => -1));
        ?>

        <?php $metabox->the_field('case-study-link'); ?>

        <p id="case-study-select">    

            <label>Which case study goes here?</label>

                <?php foreach ( $mypostype as $mypost  ) { ?>

                   <input type="radio" name="<?php $metabox->the_name(); ?>" value="<?php echo get_permalink_by_name(  $mypost->post_name  ); ?>" <?php echo $checked; ?>> 
                   <?php echo $mypost->post_title; ?>
                <?php }  ?>
        </p>

在foreach循环中使用的问题显然是每个单选按钮都被视为已选中,因此列表中的最后一个按钮始终是标记的。如何修改它以确保真正选择的按钮被标记为?

注意:功能按预期工作 - 当您选择案例研究时,会在页面中插入正确的链接,但在后端,错误的项目将显示为已选中。

1 个答案:

答案 0 :(得分:1)

$i = 0;//set counter
foreach($foo as $bar) {
     if($i == 0) { $checked = "checked";}else {$checked = '';}
     //radio button stuff here...+ stuff with $bar...
     echo "<input type='radio' name='my_radio' value='{$bar}' {$checked}>";
     $i++;

}

默认情况下,将选择第一个选项,但会根据所选的单选按钮值

更改这些值