Introduction and purpose
In HTML, there is no control for multi select dropdown, we need to write our own logic. Here, I am going to exlpain with a small example. To accomplish our task, we used jQuery and CSS, using HTML.
HTML code
Here, we created a div tag in which we used simple input text field. On clicking text box, we are binding another div (in our example id='divmulti'), using jQuery.
- <div> <input type="text" id="txtmulti" onclick="multishow()" />
- <div id="divmulti" class="multiselect" style='width: 172px; overflow-y: scroll;height: 90px; display:none'> <label><input type="checkbox" value="Green"/>Green</label> <label><input type="checkbox" value="Red"/>Red</label> <label><input type="checkbox" value="Blue"/>Blue</label> <label><input type="checkbox" value="Orange"/>Orange</label> <label><input type="checkbox" value="Purple" />Purple</label> <label><input type="checkbox" value="Black" />Black</label> <label><input type="checkbox" value="White"/>White</label> </div>
- </div>
If you want to add dynamic data to display, loop the data and dynamically add the label element.
CSS code
- <style type="text/css">
- .multiselect {
- width: 20em;
- height: 15em;
- border: solid 1px #c0c0c0;
- overflow: auto;
- }
-
- .multiselect label {
- display: block;
- }
-
- .multiselect-on {
- color: #ffffff;
- background-color: #000099;
- }
- </style>
jQuery code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>. This tag is mandatory for us to show the checkboxes and maintains the state of it.
- <script type="text/javascript">
- jQuery.fn.multiselect = function() {
- $(this).each(function() {
- var checkboxes = $(this).find("input:checkbox");
- checkboxes.each(function() {
- var checkbox = $(this);
-
- if (checkbox.prop("checked")) {
- checkbox.parent().addClass("multiselect-on");
- }
-
- checkbox.click(function() {
- var checkbox = $(this);
- if (checkbox.prop("checked")) {
- checkbox.parent().addClass("multiselect-on");
- var category = $('#txtmulti').val();
- if ($.trim(category) != "") {
- $('#txtmulti').val(category + "," + $(this).val());
- $(this).val();
- } else {
- $('#txtmulti').val($(this).val());
- }
- } else {
- checkbox.parent().removeClass("multiselect-on");
- var category = $('#txtmulti').val();
- category = category.replace($(this).val(), "").replace(',,', ',');
- $('#txtmulti').val(category);
- }
- });
- });
- });
- };
- $(function() {
- $(".multiselect").multiselect();
- });
-
- function multishow() {
- $('#divmulti').show();
- }
-
- function removemultishow() {
- $('#divmulti').hide();
- }
- </script>
Conclusion
Furthur, we can add more CSS to improve UI but the logic remains the same.