jQuery Chosen plugin add options dynamically

Solution 1:

First, you need to add the <option>s to the <select> that Chosen was bound to. For example:

$('.blah').append('<option value="foo">Bar</option>');

Then, you need to trigger the chosen:updated event:

$('.blah').trigger("chosen:updated");

More information can be found here (although you need to scroll down to Change / Update Events).


Update 7th August 2013

The event name has changed to chosen:updated since version 1.0 (July 2013) as Tony mentions in the comments. The updated documentation can be found here.

Solution 2:

newest chosen version changed the event name to "chosen:updated"

so your code will be like this:

$('.blah').append("<option value='"+key+"'>"+value+"</option>");
$('.blah').val(key); // if you want it to be automatically selected
$('.blah').trigger("chosen:updated");

Solution 3:

You can call this function to add element to chosen after you save the element to server using Ajax:

function appendToChosen(id,value){
    $('.blah')
        .append($('<option></option>')
        .val(id)
        .attr('selected', 'selected')
        .html(value)).trigger('liszt:updated');
}

Ajax call:

$.ajax({
    type: 'POST',
    url: 'savepage.php',
    data: $('#modal-form form').serialize(),

    success: function(data, status) {
        appendToChosen(data[0],data[1]);
    },
    error: function (response) {
        alert(response);
    }
    }).always(function(data, status) {
        //hide loading
    });