how do I keep a selected option after sending a form with plugin select2

0

I have the following code, I am trying to build an excel-like filter with the select2. well the filter works and it makes the consultations, but I would like to leave or remember the selected options, since if I make a query and then another ... the previous selection is lost ..

in php with codeigniter I have:

    echo form_open(base_url().'modificar_'.$tabla);
    foreach ( $campos as $campo => $valor )
    {
        foreach ($pops as $fila)
                $aux[]=$fila->$campo;
        $registro=array_unique($aux);
        unset($aux);
        $cuenta=sizeof($registro) - in_array('',$registro);
        // Voy imprimiendo el primer select
        echo "<th>".$cuenta." <div class='input-group input-group-sm'><select name='".$campo."[]' id='".$campo."[]' class='form select2' multiple='multiple' data-placeholder='$nombres[$campo]'>";
        echo "<option value='N'>$nombres[$campo]</option>";
        foreach( $registro as $valor2 )
        {
            echo "<option value='".$valor2."'";
            if ( $valor2 == $valor && $valor != "" )
                echo "selected='selected'";
            echo ">".$valor2."</option>";
        }
        echo "</select><span class='input-group-btn'>
                  <button type='button' class='btn btn-info btn-flat' onclick='this.form.submit();'>Go!</button>
                </span>
          </div>";
        echo "</th>";
    }
    echo form_close();

and in my view I have the following javascript:

<script>
  $(function () {
    $('.select2').select2()
       })
</script>

Even though I have the selected one, it does not leave the selected options.- Could someone help me?

    
asked by Kevin Infante 28.07.2018 в 02:34
source

1 answer

0

I found the solution, in the view modify the script so that it builds the array of selected elements: in my case I take them from the form I send ... greetings

<script>
  $(function () {
    //Initialize Select2 Elements
      <? echo "var preload_data = [";
       foreach($campos as $clave => $valor)
                if($this->input->post($clave))
                    foreach($this->input->post($clave) as $vall)
                            echo  "'".$vall."',";
                        echo "];";
                   ?>
   //   var preload_data = ['Kevin','Hector','CRM Austral'];
     // alert(preload_data);
    $('.select2').select2()
      $('.select2').val(preload_data).trigger('change');
       })
</script>
    
answered by 01.08.2018 в 00:33