Implementing multiselect dropdown

 

select2 is one of the nicest jQuery libraries available for web site development. It gives the web developer a lot of power in creating select boxes.

In this post I would like to discuss how to implement a multiselect dropdown in PHP using select2

When we need to select multiple options from a list of many options. Multi checkbox will also work, but the UI of it will not be as neat as multiselect dropdown.

Initial UI of shifts page
227d62ea-2bf5-11e6-8159-7bfe52680de0

In the above image. We can see all the rooms. It becomes tough for the user to select and go through each one of them and the UI also looks clumsy. After implementing multi select dropdown UI looks like the below image.

After implementing multiselect dropdown UI looks likes this.

5ea7d648-3d15-11e6-9901-3341dbc49a91

Once we select rooms/Angel type/Occupancy. The list of options will be visible as a drop-down.

Implementation

Library used for implementing multiselect dropdown is select2 we can download the select2 Library from here Download

CODE

Cdn links for js and css files should be added

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

We need to call this function whenever we need to implement a multi select drop containing the $items in its list.

// $items = items for multiselect dropdown

function multiple_select($items, $selected, $name, $title = null){ 
  $html_items = array();
  if (isset($title))
      $html .= '<h4>' . $title . '</h4>' . "\n";
  // assigning the items to multiple
  $html .= '<select multiple id="selection_' . $name . '"  class="selection ' . $name . '" style="width:200px">';

  foreach ($items as $i)
    $html_items[] = '<option  value="' . $i['id'] . '"' . '>' . $i['name'] . '</option>';
  $html .= implode("\n", $html_items);
  $html .= '</select>';
  $html .= '<input type="checkbox" id="checkboxall_' . $name . '"  >All' . '<br>';
  $html .= '<input type="checkbox" id="checkboxnone_' . $name . '"  >None';
  // javascript for multiselect
  $html .= '$("#' . "selection_" . $name . '").select2({
  placeholder: "Select",
    });
  });
  ';
    return $html;
}

Englesystem

Development: https://github.com/fossasia/engelsystem

Issues/Bugs: Issues

 

Continue ReadingImplementing multiselect dropdown