Adding text other than the selected text options to the select with the Chosen plugin

namretiolnave picture namretiolnave · Sep 9, 2013 · Viewed 13.2k times · Source

I am using the chosen plugin.

Adding this to my document does not enable me to type into the text field and add a new item to the list.

$(document).ready(function (){    
    $(".chosen-select").trigger("chosen:updated");
});

This will allow some hard coded text to be added to the list:

$(document).ready(function (){
    $('.chosen-select').chosen();
    $('.addsomething').click(function (){
        $(".chosen-select").prepend("<option>Utopia</option>");
        $(".chosen-select").trigger("chosen:updated");
    });
});

What I would like to see happen is I would like to be able to add text to the text field, hit return and have my entry be added if I have not chosen it. It does not need to be permanently added to the options list.

Answer

Bogdan picture Bogdan · Sep 9, 2013

Not sure if it can be done in an easier way, but this works just fine. The comments from the code explain each step:

var select, chosen;

// Cache the select element as we'll be using it a few times
select = $(".chosen-select");

// Init the chosen plugin
select.chosen({ no_results_text: 'Press Enter to add new entry:' });

// Get the chosen object
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");
    }
});

Here's a working example: http://jsfiddle.net/jHvmg/436/