Attach click-event to element in .select2-result

brckmann picture brckmann · Mar 26, 2013 · Viewed 59.1k times · Source

I'm looking for a way to attach a click-event to a select2-result-item. I've gone ahead and formatted both result and selection via

function format(state) {
    if (!state.id) return state.text; // optgroup
    return state.text + " <i class='info'>link</i>";
}

to add an "info"-icon I'm now trying to attach a simple click-event to the .info-element but can't get this to work:

$('.info').on('click', function(event){
    event.preventDefault();
    alert("CLICK");
    $('#log').text( "clicked" );
});

Any help? Anyone with a similar problem? Is this possible at all?

I prepared a jsFiddle at: http://jsfiddle.net/s2dqh/3/

Answer

ant_Ti picture ant_Ti · Mar 26, 2013

Because Select2 lib prevent any click events on popover list you can't bind events to .info directly. But you can redefine onSelect method and place there any code you want.

See example: http://jsfiddle.net/f8q2by55/

Update for multiple selects: http://jsfiddle.net/6jaodjzq/