简体   繁体   中英

How can i make to php write only once selected to the list?

Im going to make a html list with php what is the default value is the current day,month or year.

like this:

在此处输入图片说明

Here is the code:

while ($start <= $end) {
    if ($start == date("Y") || $start == date("d")  || $start == date("m")) {
        echo "<option selected value='$name'>$start</option> <br>";
    } else {
        echo "<option value='$name'>$start</option> <br>";
    }
    $start++;
}
    
echo "</select>";

The problem is the logic is not working fine, because at the day or month cant be separated and it always make 2 selected item in html, and and always applies the last one.

htmllius

Anyone can help me to solve this problem? Any tips, maybe this is not the good way for this.

Set a variable to compare with depending on which dropdown you're creating, which is appareently in the $name variable. Then you won't mistakely select the Day value that matches the current month, or vice vera.

if ($name == 'Year') {
    $selected = date('Y');
} elseif ($name == 'Month') {
    $selected = date('m');
} elseif ($name == 'Day') {
    $selected = date('d');
}

while ($start <= $end) {
    if ($start == $selected) {
        echo "<option selected value='$start'>$start</option> <br>";
    } else {
        echo "<option value='$start'>$start</option> <br>";
    }
    $start++;
}
    
echo "</select>";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM