Skip to content

Programmatically de select option values

yanickrochon edited this page Jan 9, 2013 · 2 revisions

If you have to manipulate your <SELECT> element to dynamically add or remove (or modify) <OPTION>s, then you need to refresh the multiselect widget to take changes into account. Since there is no native (or generic/clean) way to automatically notify when a parent element has children added or removed (or even modified), the script modifying the element is thus responsible to trigger or notify all interested parties about the changes. This requirement is done really easily with multiselect.

####See a working demo here.

$(selector).multiselect(options);   // initialize the widget as usual

function someActionCallback() {
    // find all selected options
    var selected = $(selector).find('option:selected');
    // selected.remove();  // remove all selected
    // find all unselected options
    var available = $(selector).find('option:not(:selected)');
    // available.remove();  // remove all available

    // append some new option
    $(selector).append('<option value="someValue">Some Value</option>');
    // modify the third option (0 based index)
    $(selector).find('option:eq(2)').text("New value!").val('newVal');
    
    $(selector).multiselect('refresh');  // update changes
}