Reputation: 874
I am populating data from database to radio button and want to check the first value as default but I have no idea on how to do it. Here is my coding that I've done so far.
View
<?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 }}; ?>
If I add 'checked' => TRUE
in $designThemesAttr = array()
the system will check the last value of radio button as the default, but I wanted to check the first value.
Upvotes: 1
Views: 481
Reputation: 525
solved your issue you can set it by conditional statement as replace your code by this
<?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++; }}; ?>
Upvotes: 2
Reputation: 26268
'checked' => TRUE
in $designThemesAttr = array() the system will check the last value of radio button as the default. This is right, because you doing it inside a for loop, and only one radio remains selected inside a group. So the last one is showing checked.
So maintain a variable to count the iteration like:
$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.
}
Upvotes: 0