In the previous recipe, we used Chosen. In this recipe, we will take a deeper look into the creation of simple select boxes, making one the most user-friendly way pickers out there.
In this recipe, we will use Chosen (https://github.com/harvesthq/chosen) and its dependency jQuery by adding them from a CDN.
We create an HTML file and the accompanying JavaScript code:
<head> <meta charset="utf-8"> <title>Single select list</title> <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/chosen/0.9.11/chosen.css"> <style type="text/css"> .drop-down{ width: 250px; } </style> </head>
select
elements with several available options:<form> <div> <label> Favorite programming language: <select id="programming" data-placeholder="Your favorite programming language" class="drop-down"> <option value=""></option> <option>Java</option> <option>Python</option> <option>Clojure</option> <option>C</option> <option selected>Java Script </option> <option>Lisp</option> <option>Pascal</option> <option>VB</option> </select> </label> </div>
optgroup
element:<div> <label> You consider your self to be a: <select id="occupation" data-placeholder="Occupation" class="drop-down"> <optgroup label="Software"> <option>Java developer</option> <option>Node developer</option> <option>Software Achitect</option> <option selected>Engineer</option> <option>Manager</option> <optgroup> <optgroup label="Hardware"> <option>Semiconductor</option> <option>Manager</option> <option>Computer Hardware Engineer</option> </optgroup> </select> </label> </div>
<input type="submit" /> </form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/0.9.11/chosen.jquery.min.js"></script>
$(function() { $("#programming").chosen({ allow_single_deselect:true }); $("#occupation").chosen(); });
The best thing about Chosen is its simplicity; we just select the elements with jQuery and apply the plugin. There is an option allowing deselect that we can enable during creation of these kind of elements:
$("#programming").chosen({allow_single_deselect:true});
Also, we can add an attribute named data-placeholder
that will contain default text, such as Occupation
, as in our example. If this is not specified, it will default to Select Some Option
for single select.
If you need to use data for the options that will change after the initial creation of Chosen, you can update the component dynamically and then trigger the liszt:updated
event on the selected field. The
liszt:updated
event is a Chosen-specific internal event. Chosen, after calling the event, will rebuild the list based on the updated content. For example, on an element with ID as countries
, the triggering would be as follows:
$("#form_field").trigger("liszt:updated");
3.15.182.62