Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 multiple-select - programmatically deselect/unselect item

I have a select2 list and a set of external buttons. I wanted to click the external buttons and unselect corresponding items in the select2 list. I know I can do item selection from external value using the command

$("#external_btn").click(function() {
    $("#select2").val("CA").trigger("change");
});  

So when I click on the "external_btn" button, the "ca" item will be selected on the select2.

But how I can do item unselection? Thanks.

like image 711
user3145427 Avatar asked Mar 03 '14 22:03

user3145427


2 Answers

There does not appear to be a built-in function to programmatically deselect/unselect an option from a multiple-select Select2 control. (See this discussion.)

But you can get the array of selected values, remove the value from the array, and then give the array back to the control.


Select2 v4:

The following code works for Select2 v4. It also works for Select2 v3 as long as the control is backed by a <select> element, rather than a hidden input element. (Note: When using Select2 v4, the control must be backed by a <select> element.)

var $select = $('#select');
var idToRemove = 'c4';

var values = $select.val();
if (values) {
    var i = values.indexOf(idToRemove);
    if (i >= 0) {
        values.splice(i, 1);
        $select.val(values).change();
    }
}

JSFiddle for Select2 v4

JSFiddle for Select2 v3


Select2 v3:

The following code works for Select2 v3, regardless of whether you back the control with a <select> element or a hidden input element.

var $select = $('#select');
var idToRemove = 'c4';

var values = $select.select2('val'),
    i = values.indexOf(idToRemove);
if (i >= 0) {
    values.splice(i, 1);
    $select.select2('val', values);
}

JSFiddle for Select2 v3, using <select> element

JSFiddle for Select2 v3, using hidden input element

like image 59
John S Avatar answered Nov 09 '22 23:11

John S


As you've indicated in your question, you can modify the state of the underlying select element and then trigger a change. So then you can simply deselect an option in the same way you might with a regular select.

Assuming an option of value "val", the following code would deselect it:

$("#select option[value=val]").prop("selected", false)     // deselect the option
                              .parent().trigger("change"); // trigger change on the select

http://jsfiddle.net/9fD2N/3/

like image 45
James Montagne Avatar answered Nov 10 '22 00:11

James Montagne