[英]How to set preselected options into a multiple select tag according to a php array
I have made a multiple select tag and I would like some of its options to be selected according to given PHP array $attr 我已经制作了一个多选标签,我希望根据给定的PHP数组$ attr选择一些选项
<select multiple="multiple" name="isattr[]" id="editAttr">
<?php
while($attrresult = mysqli_fetch_array($attrfetch)) {
echo "<option>".$attrresult[attr_title]."</option>";
}
?>
</select>
So if the select
tag has the options "Manager" "Programmer" "Teacher" and $attr
contains the values "Manager" and "Programmer", these options should be preselected. 因此,如果
select
标签具有选项“Manager”“Programmer”“Teacher”和$attr
包含值“Manager”和“Programmer”,则应预先选择这些选项。
Use in_array()
to check if the value is in the $attr
array, and apply the selected property to the element based on that : 使用
in_array()
检查值是否在$attr
数组中,并根据该元素将selected属性应用于该元素:
<select multiple = "multiple" name = "isattr[]" id = "editAttr" >
<?php
$attr = array("Manager", "Programmer");
while ($attrresult = mysqli_fetch_array($attrfetch)) {
$selected = in_array( $attrresult[attr_title], $attr ) ? ' selected' : '';
echo "<option".$selected.">".$attrresult[attr_title]."</option>";
}
?>
< /select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.