Pergunta

I have a working jquery multi select. the page/form, when submitted posts back to itself with the options in the multi select manipulating the data displayed.

the problem I am having is that I am unsure how to populate the selected options in the multi select list, based on the posted form values.

so for example, my multi select is populated with 3 options from my database. apples, pears, oranges. i select apples and pears so oranges is still unselected.

when the page submits and reloads, all three options are again unselected. I want apples and pears to still be selected and use teh post info to do this.

I am using codeigniter so have the following in my controller:

$sections = $this->_model()->getsections();
        $sectionstr = '<option value=""> </option>';
        if ( $sections !== "false") {
          foreach ($sections as $key => $value) {
            if ( $key === 0 ) {
            }
            else {
              $sectionstr = $sectionstr.'<option  value="'.$key.'">'.$value.'</option>'."\n";
            }
          }
        }

my post array is contained in a variable:

$sectionval=$this->input->post('section');

How can I modify the controller foreach loop to look in the array, if it exists then mark it as selected?

so the line output would be

 $sectionstr.'<option selected value="'.$key.'">'.$value.'</option>'."\n";

Thanks as always,

Foi útil?

Solução

Modifiy your code as below

$sections = $this->_model ()->getsections ();
    $sectionval=$this->input->post('section');
    $sectionstr = '<option value=""> </option>';
    if ($sections !== "false") {
        foreach ( $sections as $key => $value ) {
            if ($key === 0) {
                continue;
            }
            $selected = $sectionval == $value ? 'selected="selected"' : '';

            $sectionstr = $sectionstr . '<option  value="' . $key . '" ' . $selected . '>' . $value . '</option>' . "\n";
        }
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top