单击时更改Select2选项



我在我的表单中使用的select services_dd上使用select2插件,我在页面上有一个 .js-autoselect的链接。单击此时,我想使用该链接标签的ID并根据他们单击的按钮更改Select2选项。

<option>值属性匹配链接上ID的属性。下面的代码正在成功更改值,但是Select2没有更新,它仍然显示第一个选择。

$('.js-autoselect').click(function(e){
    e.preventDefault();
    var option = $(e.target).attr('id').trim().toLowerCase(); // option =link1
    $('#services_dd option:selected').val(option);
    alert($('#services_dd option:selected').val()); // this alerts link1 which is correct
});

有人知道如何更新Select2

$("#services_dd").select2("val", option);

请参阅文档的编程访问部分:http://ivaynberg.github.com/select2/#documentation

工作示例

基于 @scoota269的答案,我写了以下JS小提琴,显示了此功能:https://jsfiddle.net/robertmassaioli/ro2279ts/5/

应该能够帮助您查看如何完成此工作。

代码

以防万一JS小提琴被关闭:

$(function() {
    var select = $("#the-select");
    select.select2();
    $("#update").click(function() {
        // How to remove a value
        select.find("option[value=1]").remove();
        // How to add a value
        select.append("<option value='5'>Five</option>");
        select.select2();
    });
    $("#select").click(function() {
        // How to select a value
        var current = select.select2("val");
        current = current || [];
        current.push(2);
        select.select2("val", current);
    });
});
$('#mySelect2').val('US'); // Change the value or make some change to the internal state
$('#mySelect2').trigger('change.select2'); // Notify only Select2 of changes

我认为您应该简单地做

$('#services_dd').val(option);
alert($('#services_dd').val());

否则,在代码中,您只会更改所选选项的值属性(而不是选择元素的值)。

最新更新