How to Add text to the select with the chosen plugin
By Tan Lee Published on Feb 16, 2024 457
This post shows you How to Add text to the select if not exists with the chosen plugin
For example:
<select id="#ddlFoxLearn" class="chosen-select"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> <option value="4">Option 4</option> <option value="5">Option 5</option> </select>
Adding css to your html file
<link rel="stylesheet" href="/css/chosen.css" />
Adding javascript to html file
<script src="/js/jquery-3.3.1.min.js"></script> <script src="/js/chosen.jquery.min.js"></script>
Finally
<script type="text/javascript"> $(document).ready(function () { var select = $("ddlFoxLearn"); // init the chosen plugin select.chosen({ no_results_text: 'Press enter to add new entry.' }); // var chosen = select.data('chosen'); // Bind the keyup event to the search box input chosen.dropdown.find('input').on('keyup', function (e) { // if we hit Enter and the results list is empty (no matches) add the option if (e.which === 13 && chosen.dropdown.find('li.no-results').length > 0) { var option = $("<option>").val(this.value).text(this.value); // add the new option select.prepend(option); // automatically select it select.find(option).prop('selected', true); // trigger the update select.trigger("chosen:updated"); } }); }); </script>
Opening your html file, If everything works fine, you will see as shown below.
Categories
Popular Posts
HTML Bootstrap 4 Login, Register & Reset Template
Nov 11, 2024
Responsive Animated Login Form
Nov 11, 2024
Material Lite Admin Template
Nov 14, 2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
Nov 17, 2024