简体   繁体   中英

Keep value selected in the drop down even after form has been submitted iin php

<?php

?>

/* Array to store days in a week*/
 $NoofDays=array("Monday","Tuesday","Wednesday","Thurseday","Friday","Saturday","Sunday");

?>
<div class="form-wrapper">
<form action=""  method="post">
     <select name="days">
         <?php foreach($NoofDays as $days){?>

        <option <?php if( $daysTitle== '$days')?> selected="selected"> <?php echo $days;?></option>

        <?php } ?>
    </select>
    <button type='submit' class="btn">Submit me</button>
</form>`enter code here`
  </div>
<?php
/* Script to generate the Switch case */
    if (isset($_POST['days'])) {
        $selected = $_POST['days'];


    switch ( $selected) {
        case "Monday":
            echo "Laugh on Monday, Laugh for danger";
            break;
        case "Tuesday":
            echo "Laugh on Tuesday, Laugh for stranger";
            break;
        case "Wednesday":
            echo "Laugh on Wednesday,Laugh for Letter";
            break;
            case "Thurseday":
            echo " Laugh on Thurseday,Something better";
            break;
            case "Friday":
            echo "Laugh on Friday,Laugh for sorrow";
            break;
            case "Saturday":
            echo "Laugh on Saturday,Joy Tommorow!";
            break;

        default:
            echo "Laugh on Every day for some reason:)";
    }
        }
?>

Thanks anyone for answering the question. Format the code will make it easier to visible the errors. This is PHP code (PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language)

<option <?php if (isset($_POST['days']) && $_POST['days'] === $days): ?>selected="selected"<?php endif; ?>><?php echo $days; ?></option>
<select name="days">
<?php
foreach($NoofDays as $day)
{
    $selected = (!empty($_POST['days']) && $_POST['days'] == $day) ? ' selected="selected"' : '';
    echo sprintf('<option value="%s"%s>%s</option>', $day, $selected, $day);
}
?>
</select>

even better: use any third party template engine - PHP alone is an ugly one.

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