6

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?

bobdev
  • 143
  • 2
  • 2
  • 7

2 Answers2

10

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

Community
  • 1
  • 1
lsklyut
  • 366
  • 3
  • 7
  • I was actually referring to the displayed selected tags (not in search result dropdown). But the above works by using the selectChoice instead of onSelect. E.g. "search.selectChoice = (func..." – bobdev Jan 30 '14 at 08:37
  • This does not work on latest select2 versions (4.1.0) – suomi-dev Jan 17 '23 at 14:58
7

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"
        }
    ]
}
Michal Lohniský
  • 575
  • 5
  • 10
  • 7
    In version 4+ the select event is `select2:selecting`. From [this SO answer](http://stackoverflow.com/a/18615267/997596) – Fisu Oct 01 '15 at 08:31