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 f开发者_高级运维or 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>';
}
Use the in_array() function.
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>";
}
}
Very simple with the help of jQuery where the select has the id test
$('#test option').attr('selected', 'selected');
JSFiddle Example
精彩评论