0

I added checked=checked, but the last option was selected. I want the first option. How can I do that?

<?php


         if ($options) { ?>
          <?php $i=1; foreach ($options as $option) { ?>

            <?php if ($option['type'] == 'select') { ?>
                <?php if($i==2) {    $s=0;?>
                <div id="option-<?php echo $option['product_option_id']; ?>" class="mug_option" style="float:left; width:45%;">
                  <?php echo $text_imprint_side1;?>

                  <?php foreach ($option['option_value'] as $option_value) { ?>

                  <div><input type="radio" checked="checked" name="mug_option[<?php echo $option['product_option_id']; ?>]" value="<?php echo $option_value['product_option_value_id']; ?>" id="mug-option-value-<?php echo $option_value['product_option_value_id']; ?>" class="color_opt" />
  <label for="mug-option-value-<?php echo $option_value['product_option_value_id']; ?>"><?php echo $option_value['name']; ?>
   <?php if ($option_value['price']) { ?>
    <input type="hidden" name="opt_price" id="opt_price<?php echo $option_value['product_option_value_id']; ?>" value="<?php echo $option_value['price_without_symbol']; ?>" />
   <?php } else { ?>
    <input type="hidden" name="opt_price" id="opt_price<?php echo $option_value['product_option_value_id']; ?>" value="0" />
   <?php } ?>

  </label>
  </div>
                 <?php } ?>
                </div>
                <?php } ?>
TRiG
  • 10,148
  • 7
  • 57
  • 107
user7441072
  • 285
  • 1
  • 4
  • 17
  • 3
    Possible duplicate of [How to select a radio button by default?](https://stackoverflow.com/questions/5592345/how-to-select-a-radio-button-by-default) – Omis Brown Aug 31 '17 at 10:43
  • 1
    in `foreach` loop you checking each radio button so you just end up with last one checked – ArtOsi Aug 31 '17 at 10:51
  • Possible duplicate of [Assign an initial value to radio button as checked](https://stackoverflow.com/questions/4711036/assign-an-initial-value-to-radio-button-as-checked) – But those new buttons though.. Sep 03 '17 at 07:10

1 Answers1

1

This is because the foreach loop adds the check for all radio options, so the last one will be checked by default. You need to add an if condition in the foreach loop like this:

<?php
$i=1; 
foreach ($option['option_value'] as $option_value) {
    ?><div><input type="radio" <?php if($i==1) {echo "checked='checked'"; $i++;
} ?> ......blah blah blah
TRiG
  • 10,148
  • 7
  • 57
  • 107