有没有办法检索已经在下拉 select 选项上设置的值?

Is there a way to retrieve a value that has already been set on a dropdown select option?

我有一个 create.php 用于创建用户,edit.php 用于编辑学生信息。

我是 PHP 的初学者,所以如果这可能是一个有非常简单方法的问题,请告诉我。

我一直在寻找检索已在下拉菜单中设置的值,但我发现的唯一内容是:

a.) 他们只打印选择的值,不检索已经设置的选项。

示例代码:

    <p>Schedule</p>
    <select value="<?= $data->schedule; ?>" name = "schedule">
    <?php
    $schedule = array ('Morning', 'Afternoon');
    foreach ($schedule as $sched) { ?>
      <option value="<?php echo $sched; ?>"><?php echo $sched; ?></option>
    </select>
    <?php } ?>

b.) 我不了解 javascript,我试过了,但由于我不了解,所以我似乎无法让它工作。

我试过的示例代码:

    <p>Schedule</p>
            <select id = "my_select" name = "schedule">
              <option id = "o1" id="id1">Morning</option>
              <option id = "o2" id="id2">Afternoon</option>
            </select>
    <script type="text/javascript">
    $("#my_select").change(function() {
      var id = $(this).find('option:selected').attr('id');
    });
    </script>

我也试过了

document.getElementById('schedule').selectedOptions[0].text

但还是没有输出"afternoon"

这是我最后的选择,因为我找不到其他资源。

I added a picture of what I wanted to do since my question might be a little confusing.

选择使用 selected 属性而不是值来定义选定状态。

因此在您的代码中检查值然后应用 selected

<p>Schedule</p>
<select name="schedule">
<?php foreach (['Morning', 'Afternoon'] as $sched): ?>
    <option value="<?= $sched ?>"<?= ($data->schedule == $sched ? ' selected' : null) ?>><?= $sched ?></option>
<?php endforeach ?>
</select>