Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event in select2 tag with a link

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?

like image 669
bobdev Avatar asked Jan 25 '14 10:01

bobdev


2 Answers

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

like image 159
lsklyut Avatar answered Sep 30 '22 02:09

lsklyut


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"
        }
    ]
}
like image 29
Michal Lohniský Avatar answered Sep 30 '22 03:09

Michal Lohniský