-1

I'm a absolute newby for php and i'm struggling with just a basic thing.

I want to set a default value for a select box i have. Default value should be 2

My code

        <div class="selector-wrapper">
                <select id="adults" class="form-control" onchange="toggleSetGuests()">
                <?php
                for($i = 0; $i <= 20; $i++):
                ?>
                <option value="<?php echo $i ?>" <?php if($i == 0){ echo('selected="true"'); }  ?>>
                    <?php echo $i ?> Adults
                </option>
                <?php
                endfor;
                ?>
                </select>
        </div>

So in this select box i get options from 0 - 20. I want to set the default value as 2 instead of 0

My approach was like below

<option value="<?php echo $i ?>" <?php if($i == 2){ echo('selected="true"'); }  ?>>

But did not work.

How do i set the default value to be selected as the value 2

CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • 1
    `selected="selected"` ? – nice_dev Mar 31 '20 at 10:31
  • Does this answer your question? [How can I set the default value for an HTML – El_Vanja Mar 31 '20 at 10:34
  • The example code is working just fine. Tested on PHP 5.6 - 7.4. Maybe it's some kind of issue with the surrounding HTML? – gstoert Mar 31 '20 at 10:35

1 Answers1

1
<option value="<?php echo $i ?>" <?php if($i == 2){ echo ' selected'; }  ?>>

should work.You don't need selected=true

Die-Bugger
  • 166
  • 8