always trigger "change"-event for <select>, even if the select2-option clicked is already selected
Asked Answered
G

6

3

I have a native <select>-element based on which I'm initializing a select2-dropdown-menu. I bound a change-event via select2 which is called whenever the select2/select-option is changed. However, I need to fire the event even if the currently selected option is selected again.

function onSelectChange(){
    alert('changed');
};

$("#select").select2().bind('change', onSelectChange);

I prepared a http://jsfiddle.net/rb6pH/1/ - if "Alaska" is currently selected and then selected again via the select2-dropdown, onSelectChange() should fire again, triggering the alert.

I have a hard time expressing myself, please ask if something isn't clear enough.

Grayback answered 10/5, 2013 at 15:59 Comment(14)
I can't get to fiddle at the moment, can you post a link to the plugin you are using?Flax
ivaynberg.github.com/select2Grayback
If you want to fire an event on every click, why not just use the click() method?Hubing
This doesn't sound like good UX design. If the value doesn't change the user probably wont expect anything else to change.Kisner
@FritsvanCampen I def. hear you on that and basically agree, however the situation is a little more complicated; thus, I need to trigger 'change' even when nothing is changed :(Grayback
Can you explain your situation? Maybe there is some other event you can listen to.Kisner
There is a mousedown event being listened to inside the plugin that detects whether or not the change event needs to be triggered. you're going to need to override that event to instead trigger it anyway. github.com/ivaynberg/select2/blob/master/select2.js#L1882Flax
@DavidThomas I need to fire the event whenever an option is selected via the select2-dropdown, which, as far as I understand, happens via change, not clickGrayback
@FritsvanCampen I'll try: I'm using multiple select2-dropdowns to switch/display page content dynamically. Each select2-dropdown represents the navigation for a different content-category. Furthermore, I use a transparent element placed above the left part of the select2-element to capture clicks to the select2-element so that only the dropdown-arrow to the far right of the select2-element actually triggers the select2-dropdown; a click on the transparent element displays the content corresponding to the currently selected select2-option.Grayback
Sorry, that makes absolutely no sense at all. It's 2013, you shouldn't be working with transparent elements to capture clicks anymore.Kisner
I think you should ask a question about the problem you're trying to solve (with this covoluted approach), rather than how to deal with the problems created by the solution you're trying. Further, please take a look at the 'What is the XY problem?'Hubing
@FritsvanCampen However, the user still may use the select2-dropdown to select an option. If the users last selection had been in dropdown B and he then wants to select the option in dropdown A which is already selected, the change-event needs to trigger. I hope at least the explanation makes sense - I know using select2 here does not, however the design choice to even use select2 here currently is beyond my reach :(Grayback
So your selectboxes also act as navigation tabs? Make your own dropdownbox. The default ones don't have the behavior you want, they also don't look like navigation elements.Kisner
@FritsvanCampen I absolutely agree; but as stated in my last comment I really have no choice but going with what there is, which is select2 (used for something it wasn't designed for in the first place). You're absolutely correct with your criticism regarding using select2 as navigation tabs (even if I made them look like navigation elements ;-)).Grayback
S
4

A similar question was asked here. I have made a fiddle for your question based on the code in the link. http://jsfiddle.net/rb6pH/55/

function onSelectChange(){
alert('changed');
};

var select2 = $("#select").select2().data('select2');

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

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

    if (target) {
        onSelectChange();
        return fn.apply(this, arguments);
    }
}
})(select2.onSelect);
Sik answered 10/5, 2013 at 16:54 Comment(4)
Thanks so much Daniel, works like a charm. Ironically, the "similar question" was asked by me, too :/ Did you see the answer I just gave myself, using the "close"-event? Which approach do you find more healthy?Grayback
If you open the dropdown then click outside of it the close event will stil fire. If you want an alert to appear even if they don't select anything then I think close would be fine.Sik
Just what I realized myself this very moment (by fiddling around with the actually application code). Thanks so much again!Grayback
This code doesn't seem to be compatible with the latest version of select2 :(.Dymphia
G
6

Motivated by the absolutely valid remarks by @FritsvanCampen, I sat my ass down and figured out a way myself: What I really needed was a way to access the currently selected val, even if it hadn't changed. By using select2's undocumented close-event instead of change, I can access just that like so:

function onSelectChange(event){
    alert( $("#select").select2("val") );
};

$("#select").select2().bind('close', onSelectChange);

Find an updated jsFiddle at http://jsfiddle.net/rb6pH/42/

Grayback answered 10/5, 2013 at 16:47 Comment(1)
Still works with little adjustment: select2:close and $(this).val().Gui
S
4

A similar question was asked here. I have made a fiddle for your question based on the code in the link. http://jsfiddle.net/rb6pH/55/

function onSelectChange(){
alert('changed');
};

var select2 = $("#select").select2().data('select2');

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

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

    if (target) {
        onSelectChange();
        return fn.apply(this, arguments);
    }
}
})(select2.onSelect);
Sik answered 10/5, 2013 at 16:54 Comment(4)
Thanks so much Daniel, works like a charm. Ironically, the "similar question" was asked by me, too :/ Did you see the answer I just gave myself, using the "close"-event? Which approach do you find more healthy?Grayback
If you open the dropdown then click outside of it the close event will stil fire. If you want an alert to appear even if they don't select anything then I think close would be fine.Sik
Just what I realized myself this very moment (by fiddling around with the actually application code). Thanks so much again!Grayback
This code doesn't seem to be compatible with the latest version of select2 :(.Dymphia
R
0

I think you might refer to this link, i stuck once in same situation,

Change event is not fired when the selection is changed using Select2's val() method.

The event object contains the following custom properties:

val

the current selection (taking into account the result of the change) - id or array of ids.

added

the added element, if any - the full element object, not just the id

removed

the removed element, if any - the full element object, not just the id

For more information you might refer to this.

Thanks!

Rotate answered 10/5, 2013 at 16:16 Comment(0)
S
0

I read the question and it's so close to my problem so I decided not to post another question. What I want to do is after select2 closed, a simple text input become focused but it doesn't work. please check

function onSelectChange(){
    alert('closed');
    $('#hey').focus();
};

$("#select").select2().bind('close', onSelectChange);
$('#hey').on('focusin)', function(){alert('in');}

http://jsfiddle.net/sobhanattar/x49F2/5/

I tried to make sure that the input become focused and it showed that the input become focused but I don't know why it doesn't show the curser

Sabian answered 23/6, 2014 at 18:2 Comment(0)
P
0

a little old question but i spent a few hours last week to find a solution.

I am using Select2 version: 4.0.5.

My working solution is this one:

$("#exampleId").on("select2:open", function() {
    var checkExist = setInterval(function() {
        var $selectedChoiceInsideSelect2Dropdown = $("li.select2-results__option[id^='select2-" + exampleId + "-result'][aria-selected=true]");
        if ($selectedChoiceInsideSelect2Dropdown.length) {
            $selectedChoiceInsideSelect2Dropdown.on("mouseup", function() {
                $(this).trigger("change");
            });
            clearInterval(checkExist);
        }
    }, 100); // check every 100ms
});

It's very important to use the interval!

Perambulate answered 2/11, 2020 at 8:50 Comment(0)
S
-1
 var prev_val = $('#select2').val();
 $('#select2').blur( function() {
    if( $(this).val() == prev_val )
       // not changed
    else {
       // changed
       prev_val = $(this).val();
    }
 });
Serrulate answered 10/5, 2013 at 16:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.