How to Add text to the select with the chosen plugin

By FoxLearn 2/16/2024 9:22:17 AM   68
This post shows you How to Add text to the select if not exists with the chosen plugin

For example:

select chosen

<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.

select chosen add new