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

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/


I modified the answer from Bogdan to work with chosen 1.2.0 as well as with all types of chosen selects:

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();

// get the chosen object (any type, single or multiple)
chosen = $('.chosen-container');
// chosen = $('.chosen-select-single');
// chosen = $('.chosen-container-multi');

// Bind the keyup event to the search box input
chosen.find('input').keyup( function(e)
{
    // if we hit Enter and the results list is empty (no matches) add the option
    if (e.which === 13 && chosen.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");
    }
});