【问题标题】:Is there a way to retrieve a value that has already been set on a dropdown select option?有没有办法检索已经在下拉选择选项上设置的值?
【发布时间】:2018-03-06 13:20:40
【问题描述】:

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

选择使用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>

【讨论】:

  • 不用担心,如果您将其存储为morning 而不是Morning,则可能需要调整一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-28
  • 1970-01-01
  • 2021-11-11
  • 2012-10-31
  • 2021-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多