Click event in select2 tag with a link

Deadly 提交于 2021-01-27 05:04:14

问题


I am using select2 in tag mode. My item text is a link, e.g.:

<a href='url'>tag1</a>.

select2 seems to be swallowing the click event on the tag (selected choice) so I cannot navigate to the link.

Any ideas on how to get the link to work?


回答1:


Select2 disables click events by default and for the moment, you must use a workaround to achieve the desired results. Here's an example of how I accomplished this, thanks to the resources below. This won't work if you don't re-instantiate the variable with the return value of .data('select2')

First, add a class to your links:

<a href="#" class="detail-link">hello</a>

Then you have to listen to the onSelect event of Select2

    var search = $("#searchBox");
    search.select2({
        placeholder: "Search...",
        allowClear: true,
        minimumInputLength: 3,
        maximumSelectionSize: 1,
        escapeMarkup: function(m) { return m; },
        ajax: {     blah blah blah       },
        formatResult: window.App.formatFunction
    });


    search= search.data('select2');

    search.onSelect = (function(fn) {
        return function(data, options) {
            var target;

            if (options != null) {
                target = $(options.target);
            }

            if (target && target.hasClass('detail-link')) {
                window.location = target.attr('href');
            } else {
                return fn.apply(this, arguments);
            }
        }
    })(search.onSelect);

This question/answer/JFiddle helped me out but its important to note the .data('select2') line

EDIT: forgot the resource -- https://stackoverflow.com/a/15637696




回答2:


I use select2-selecting event:

var $q = $('#select2input');
$q.select2({
    // your settings
});

$q.on('select2-selecting', function(e){
    window.location = e.choice.url;
});

My AJAX payload looks like this:

{
    "items":[
        {
            "id": "1",
            "text": "Foo",
            "url": "/foo"
        },
        {
            "id": "8",
            "text": "Bar",
            "url": "/bar"
        }
    ]
}


来源:https://stackoverflow.com/questions/21349399/click-event-in-select2-tag-with-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!