Dynamically add option to chosen select multiple JQuery plugin

danielrvt picture danielrvt · Jul 31, 2012 · Viewed 15.6k times · Source

I want to add the text that a user inputs in the text field of a chosen select multiple input as an option, and automatically select it, all of this when the option doesn't exists, if the option exists, then I would like to select it. So far I have manage to do this:

Chosen.prototype.add_text_as_option = function () {
    $('#id_select').append(
        $('<option>')
                .html(this.search_field.val())
                .attr('selected', 'selected')
                .attr('value', 0)
    );
    $('#id_select').trigger("liszt:updated");
    return false;
};

I call this function whenever the users presses enter while the input field is in focus within the keydown_check function.

I have two problems:

  • Top priority, when the user presses enter and has typed a substring of an option, the option won't get selected, but the substring text will be added and selected. Not what I want.

For instance: If I have the option "foo", and start typing "fo", chosen will mark the first option as candidate ("foo"), so if I press enter, it should be selected, but instead, what happens is that "fo" is added as an option and selected, when I actually wanted to select "foo".

If I select "foo" with a click, then everything works fine. The option chosen marks is selected and the substring text is taken as part of the option.

How can I add a non existent option to chosen, without loosing all the original functionality?

  • How can I access the select multiple field I initilized whith chosen inside the chosen plugin? As you can see in the code above, the id of the select multiple field is hardcoded. I want to do this to be able to refresh the select when the user adds a new option.

  • The functionality that I'm looking for is very similar to the skills widget of linkedin

Answer

Jake Zeitz picture Jake Zeitz · Mar 28, 2013

You should try out the select2 plugin which is based off of chosen plugin but it works well with adding elements dynamically.

Heres the link: http://ivaynberg.github.com/select2/

Look at the example for auto-tokenization I think that might be what you are looking for.