[英]How to set multiple select options by default from array
I'm trying to retrieve options/values from my database in the from of an array i would like to set these option/values as selected by default in a multiple select list and display them to the user where they will be able to updated their data if necessary. 我正在尝试从数据库的数组中检索选项/值,我想将这些选项/值设置为默认情况下在多个选择列表中选择的选项,并将其显示给用户,以便他们能够更新其必要的数据。
//data in database
$mytitle = array(
'Arbitrator',
'Attorney',
'Student',
'Other'
);
//data for multiple select
$title = array(
'Judge' ,
'Magistrate' ,
'Attorney' ,
'Arbitrator',
'Title Examiner' ,
'Law Clerk','Paralegal' ,
'Intern' ,
'Legal Assistant',
'Judicial Assistant',
'Law Librarian' ,
'Law Educator' ,
'Attorney',
'Student',
'Other'
);
echo "<select name='title[]' multiple='multiple'>";
$test = implode(',', $mytitle);
for ($i=0; $i<=14; $i++) {
if($test == $title[$i]) {
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}
else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
echo "</select>";
I think you may have a logic error. 我认为您可能有逻辑错误。 Try this as your loop:
尝试将此作为您的循环:
foreach ($title as $opt) {
$sel = '';
if (in_array($opt, $mytitle)) {
$sel = ' selected="selected" ';
}
echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>';
}
Very simple with the help of jQuery where the select has the id test 借助jQuery非常简单,其中select具有id测试
$('#test option').attr('selected', 'selected');
Use the in_array() function. 使用in_array()函数。
for ($i=0; $i<=14; $i++) {
if(in_array($title[$i], $mytitle)){
echo "<option selected value='$title[$i]'>$title[$i]</option>";
}else {
echo "<option value='$title[$i]'>$title[$i]</option>";
}
}
foreach ($title as &$x)
{
echo "<option ".(in_array($x, $mytitle)?"selected":"")." value='$x'>$x</option>";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.