I have created an html form, and in it I have options containing the days of the month. The problem comes when I want to set today's date as selected when loading it on the page.
I have this code but it doesn't work, and just shows today and the other days of the month are gone! $day1
is date of today by date function.
<select id="day" name="day">
<?php for ($i=1 ; $i<32 ; $i++){
if($i == $day1){?>
<option value="<?php echo $i ?>" selected> <?php echo $i ?></option>
<?php}else{ ?>
<option value="<?php echo $i ?>" > <?php echo $i ?></option>
<?php }} ?>
</select>
To achieve this the default value has to match a value attribute in your option tag. That's why we are setting the selectedOption to null
The default value of the select element can be set by using the ‘selected’ attribute on the required option. This is a boolean attribute. The option that is having the ‘selected’ attribute will be displayed by default on the dropdown list. Example-1: Using the selected attribute. value for an HTML <select> element?
The defaultSelected property returns the default value of the selected attribute. This property returns true if an option is selected by default, otherwise it returns false. Note: If an option is selected by default, it is displayed first in the drop-down list. Thank You For Helping Us!
To assign default values to a selection criterion, you use the following syntax: SELECT-OPTIONS <seltab> FOR <f> DEFAULT <g> [TO <h>] .... You use the DEFAULT addition as follows to address the individual components of the first row: To fill only the LOW field (single field comparison), use: ........DEFAULT <g>.
Try to add a space between the PHP opening tag and "}else{".This works for me:
<?php
$day1=date('d');
?>
<select id="day" name="day">
<?php for ($i=1 ; $i<32 ; $i++){
if($i == $day1){?>
<option value="<?php echo $i; ?>" selected> <?php echo $i; ?></option>
<?php }else{ ?>
<option value="<?php echo $i; ?>" > <?php echo $i; ?></option>
<?php }} ?>
</select>
Actually i can't find any information about this in the documentation, other than an user contribution:
I would like to stress out that the opening tag is "
<?php[whitespace]
", not just "<?php
".
its easy possible with inline IF + echo and dot operator
<select id="day" name="day">
<?php
$day1=date('d');
for ($i=1 ; $i<32 ; $i++){
echo '<option value="'.$i.'" '. ($i == $day1 ? 'selected' : '') . '>'.$i.'</option>';
}
?>
</select>
Other days are gone because you didnt echo it out.
<select id="day" name="day">
<?php $day1=date('d'); ?>
<?php for ($i=1 ; $i<32 ; $i++){
if($i === $day1){?>
<option value="<?php echo $i ?>" selected> <?php echo $i ?></option>
<?php }else{ ?>
<?php echo '<option value="'.$i.'">'.$i.'</option>'; ?>
<?php }} ?>
</select>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With