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

问题描述 投票:2回答:1

我有一个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

但仍然没有输出“下午”

这是我的最后一招,因为我没有其他资源可以找到。

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

php selection edit dropdown
1个回答
1
投票

选择使用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>
© www.soinside.com 2019 - 2024. All rights reserved.