Click event in select2 tag with a link
Asked Answered
A

2

7

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?

Amerce answered 25/1, 2014 at 10:32 Comment(0)
H
11

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

Hummocky answered 28/1, 2014 at 13:38 Comment(2)
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..."Amerce
This does not work on latest select2 versions (4.1.0)Prosecution
P
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"
        }
    ]
}
Pga answered 16/7, 2015 at 10:47 Comment(1)
In version 4+ the select event is select2:selecting. From this SO answerUnoccupied

© 2022 - 2024 — McMap. All rights reserved.