1

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>"; 

3 Answers 3

5

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>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

small modification, if u kept the code this way, it will show all results as Selected. so what to do is if (in_array($opt, $mytitle)) { $sel = ' selected="selected" '; echo '<option ' . $sel . ' value="' . $opt . '">' . $opt . '</option>'; }else{ echo '<option value="' . $opt . '">' . $opt . '</option>'; }
0

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>";
  }
}

Comments

0

Very simple with the help of jQuery where the select has the id test

$('#test option').attr('selected', 'selected');

JSFiddle Example

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.