在选择 select2 后触发一个动作

85
我在我的搜索页面中使用了 select2 库,请问是否有一种方法可以在选择搜索结果之后触发某个操作?例如打开一个弹出窗口或简单的 JS 提示框。
$("#e6").select2({
    placeholder: "Enter an item id please",
    minimumInputLength: 1,
    ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
        url: "index.php?r=sia/searchresults",
        dataType: 'jsonp',
        quietMillis: 3000,
        data: function (term, page) {
        return {
            q: term, // search term
            page_limit: 10,
            id: 10
            };
        },
        results: function (data, page) { // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to alter remote JSON data
            return {results: data};
        },
    },

    formatResult: movieFormatResult, // omitted for brevity, see the source of this page
    formatSelection: movieFormatSelection, // omitted for brevity, see the source of this page
    dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
    escapeMarkup: function (m) { return m; } // we do not want to escape markup since we are displaying html in results
});

2
你可以绑定到“change”事件,链接中有一个名为“Events”的部分,其中包含所有不同事件绑定的非常长的代码片段。 - Ross
7个回答

181

请查看文档事件部分

根据版本不同,下面的代码片段之一应该会给你想要的事件,或者只需用"change"替换"select2-selecting"。

版本4.0+

事件现在的格式为:select2:selecting(而不是select2-selecting

感谢snakey通知我们,在4.0版本中发生了变化。

$('#yourselect').on("select2:selecting", function(e) { 
   // what you would like to happen
});

4.0版本之前的版本

$('#yourselect').on("select2-selecting", function(e) { 
   // what you would like to happen
});

仅作澄清,select2-selecting文档如下:

select2-selecting 当选择下拉列表中的选项时触发,但在对选择进行任何修改之前触发此事件。通过调用event.preventDefault(),可使用此事件允许用户拒绝选择。

相比之下,change如下所示:

change 当选择变更时触发。

因此,根据您是否希望选择完成后再执行您的事件或者可能阻止更改,change可能更适合您的需求。


14
在更新的版本中,事件可能会有其他名称(例如 'select2:select'),请参见https://select2.github.io/examples.html。 - snakey
1
文档中的事件在这里。FAQ风格不太明显。 - Pierre de LESPINAY
1
在设置值之前,会进行“选择”调用。这将导致:“console.log($(this).val())”输出空值。 - Joseph Groot Kormelink
当我在我的Angular应用中尝试相同的操作时,它会给出错误的值。假设在select2选项中有4个值,分别为1分钟、5分钟、1小时和每天。现在使用$('#yourselect').on("select2-selecting", function(e) {...},它会给出我之前选择的值而不是当前选择的值。 - Yash Jain
我尝试了$('#yourselect').on("select2-select"),function(e){...},这对我起作用了。 - Yash Jain
由于“选择”调用是在设置值之前完成的,如果有人需要选定的值,则需要将事件更改为select2:selectselect2-select,而不是select2:selectingselect2-selecting - quasar

31

关于select2事件名称已经进行了一些更改(我想是在v.4及以后),因此'-'被更改为:。请参阅以下示例:

$('#select').on("select2:select", function(e) { 
    //Do stuff
});
您可以在“select2”插件网站上检查所有事件: select2事件

14

这对我起作用:

$('#yourselect').on("change", function(e) { 
   // what you would like to happen
});

我不明白为什么,但这个方法对我有效,而Tarek的答案却不行。我甚至在另一个项目中使用了他的答案,但由于某种原因,只有这个覆盖才能让我的项目正常运行。 - tokyo0709
@tokyo0709 这段代码之所以能够工作,是因为.change事件在执行序列中比select2:select事件晚。对我来说,我试图在select2:select上捕获选择器的CSS,但即使我在检查器中看到了它,我也无法通过select2:select捕获它 - 当我改用.change时,它可以工作,因为Select2在更新原始选择器的CSS之前会触发select2:select事件... 在我看来有点疯狂。 - a20
1
@a20 有时候一个简单的解决方法是通过HTML CSS设置DOM元素的CSS,这样你就不必等待JavaScript引擎追赶了。在某些情况下它运行良好。 - yardpenalty.com

11

根据我使用的v.4版本,这将起作用。

$('#selectID').on("select2:select", function(e) { 
    //var value = e.params.data;  Using {id,text format}
});

而对于低于版本v.4的情况,这将起作用:

$('#selectID').on("change", function(e) { 
   //var value = e.params.data; Using {id,text} format
});

这对我没有用。我已将上面的代码更改为以下内容:e.params.args.data - Tushar Saxena
这对我也没有用,通过 data 字段的 e.params.data 未找到未定义的数据。经过仔细检查,e 没有设置 params 字段。对于我的问题,我只需要读取值,因此 e.val 就足够了。 - NemyaNation
@TusharSaxena e.params.args.data 对我有用,谢谢。 - Sneha

5
对于v4及以上版本:
$('#yourselect').on("select2:select", function(e) { 
     // after selection of select2 
});

4
这对我有用(Select2 4.0.4):
$(document).on('change', 'select#your_id', function(e) {
    // your code
    console.log('this.value', this.value);
});

0
//when a Department selecting
$('#department_id').on('select2-selecting', function (e) {
    console.log("Action Before Selected");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

//when a Department removing
$('#department_id').on('select2-removing', function (e) {
    console.log("Action Before Deleted");
    var deptid=e.choice.id;
    var depttext=e.choice.text;
    console.log("Department ID "+deptid);
    console.log("Department Text "+depttext);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接