Select2 multiple-select - programmatically deselect/unselect item

给你一囗甜甜゛ 提交于 2019-12-03 14:00:21

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

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/

I don't see anything to "deselect" an element. But, you can get the list of currently selected elements, remove your element and then set the value.

http://jsfiddle.net/wLNxA/

$("#e8_2").select2({
    placeholder: "Select a state"
});

$('#removeBtn').click(function () {
    // get the list of selected states
    var selectedStates = $("#e8_2").select2("val"),
        index = selectedStates.indexOf('NV'); // we're removing NV, try to find it in the selected states
    if (index > -1) {
        // if NV is found, remove it from the array
        selectedStates.splice(index, 1);
        // and set the value of the select to the rest of the selections
        $("#e8_2").select2("val", selectedStates);
    };
});

If you do not have any other event listener action on select option better :

$("#select2").val("CA").attr('checked', 'checked'); // to check
$("#select2").val("CA").removeAttr('checked'); // to un-check
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!