繁体   English   中英

HTML <Select><Option>默认基于MySQL数据

[英]HTML <Select> <Option> default based on MySQL data

我有一个简单的库存数据库,在input_data表单上,输入字段之一是field,如下所示:

<select>
    <option>In Inventory</option>
    <option>In Process</option>
    <option>Shipped/in-transit</option>
    <option>Received by recipient</option>
</select>

例如,如果我使用“处理中”输入数据,后来又想更新该垂直数据。 默认返回我的update_page.php文件中的“库存”。 我希望看到选择的“处理中”值。

这是我update_page.php中无法正常工作的代码段:

<select name="status" value="<?php echo $row['status']; ?>">
    <option>In Inventory</option>
    <option>In Process</option>
    <option>Shipped/in-transit</option>
    <option>Received by recipient</option>
</select>

“选择”在HTML中没有值属性-您可以选择多个选项,这由option元素上的所选属性确定

肮脏的方式:

<select name="status">
    <option<?php if ($row['status'] == "In Inventory"): ?> selected="selected"<?php endif; ?>>In Inventory</option>
    <option<?php if ($row['status'] == "In Process"): ?> selected="selected"<?php endif; ?>>In Process</option>
    <option<?php if ($row['status'] == "Shipped/in-transit"): ?> selected="selected"<?php endif; ?>>Shipped/in-transit</option>
    <option<?php if ($row['status'] == "Received by recipient"): ?> selected="selected"<?php endif; ?>>Received by recipient</option>
</select>

更好的方法:

 <?php
      $options = array("In Inventory", "In Process", "Shipped/in-transit", "Received by recipient");
 ?>

 <select>
     <?php foreach ($options as $option): ?>
         <option value="<?php echo $option; ?>"<?php if ($row['status'] == $option): ?> selected="selected"<?php endif; ?>>
             <?php echo $option; ?>
         </option>
     <?php endforeach; ?>
 </select>

最好的方法-将这些选项存储在数据库表中-可能最好使用ID值而不是字符串(允许更轻松地更新选项标签),并像我上面那样遍历从数据库查询中获取的可能选项。 如果此选择列表使用率很高,请缓存查询结果以获取选项(请记住,如果列表已更新,则需要清除缓存)

每个选项都有其对应的值,而不是select标记。 因此,您必须将每个选项的值与状态进行比较。

您必须检查每一个是否都是选中的,例如:

<option <?php if ($row['status'] == 'In Process') echo 'selected'; ?>>In Process</option>

如果您使用jQuery,则可以做一个更简洁的解决方案,为您的select标签指定一个ID,然后:

$(document).ready(function() {
    $('#select-id option:contains("<?php echo $row['status']; ?>")').prop('selected', true);
});

我发现的更简单的代码,仅使用JavaScript(无需jQuery)。 将其放在列表框的声明之后,然后在此处设置所选索引:

<script>
document.getElementById('listBoxId').selectedIndex=<?php echo $INDEX ?>;
</script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM