簡體   English   中英

將選擇選項默認設置為先前設置的選項

[英]Setting a select option default to a previously set option

在模態窗口中,我有一個選擇,用戶可以在其中從我的數據庫中選擇早餐。 通過選擇並提交餐食,記錄將保存在數據庫中。 但是,我想實現的是,當用戶進入同一模式窗口時,他們之前選擇的任何餐點將作為默認選項出現。 我創建了一個查詢,檢查是否已選擇餐食(optionquery1)。 有什么想法可以做到這一點? 謝謝

附帶一提,我不確定當前是否正在設置日期php變量。 日,月和年存儲在html隱藏的輸入中,但不確定如何提取值。

<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<div class="modal-body">
  <form action="my_planner.php" method="post">
  <!--<span class="test5"></span>-->
  <!--<span class="test"><input type="text" name="id_disabled" value="" disabled/>-->
  <input class="test" type="text" name="id1" value="" style="text-align:center; border:0px; font-weight:bold; font-size: 25px;"/>
  <hr class="my-4">
  <input type="hidden" name="id" value=""/>
  <input type="hidden" name="month" value=""/>
  <input type="hidden" name="year" value=""/>

<br>
<p id="breakfastTag"><br>Breakfast:</p>
<select id="breakfast" name="breakfast">
<option value="" disabled selected>Select your breakast</option>
<?
$meal='breakfast';
$date='<input type="hidden" name="id" value=""/>'.'<input type="hidden" name="month" value=""/>'.'<input type="hidden" name="year" value=""/>';
$query = $db->prepare("select * from recipe_category where categoryID=1");
$query->execute();

while ($results = $query->fetch()) {
    $recipeID=$results["recipeID"];
    $query3 = $db->prepare("select * from recipe where id=:recipeID");
    $dbParams3=array('recipeID'=>$recipeID);
    $query3->execute($dbParams3);
    $breakfast = $query3->fetchAll();

    $optionquery = $db->prepare("select * from user_planner where userID=:userID and date=:date and meal=:meal");
    $optionParams= array ('userID'=>$thisUser, 'date'=>$date,'meal'=>$meal);
    $optionquery->execute($optionParams);

    while ($results12 = $optionquery->fetch()) {
        $selectedmeal = $results12['recipeID'];
    }

    $optionquery1 = $db->prepare("select * from recipe where id=:recipeID");
    $optionParams1= array ('recipeID'=>$selectedmeal);
    $optionquery1->execute($optionParams1);

    while ($results123 = $optionquery1->fetch()) {
        $selectedrecipe = $results123['name'];
    }

    foreach($breakfast as $breakfast): ?>
        <option  value="<?= $breakfast['id']; ?>"><?= $breakfast['name']; ?></option>
    <?php endforeach;} ?>
</select>

當然可以,您需要在要顯示的<option>上使用selected屬性。 首先從第一個<option>刪除selected屬性:

<option value="" disabled>Select your breakast</option>

然后在foreach循環中,您需要一個if條件:

$results123 = $optionquery1->fetch();
$selectedrecipe = $results123['id'];

foreach($breakfast as $breakfast): ?>
    <option  value="<?= $breakfast['id']; ?>" <?php if ($breakfast['id'] == $selectedrecipe) echo 'selected' ?>><?= $breakfast['name']; ?></option>
<?php endforeach;} ?>

注意while由於我們確定Mysql僅返回一條記錄( WHERE ID = <ID> ),因此我刪除了while循環。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM