select2: Select event is not trigger if clicked on selected item
Hello,
I searched whole Internet and I didn’t find any solution so I decided to make a new issue.
Here is example: https://codepen.io/FilipK/pen/xYWrYR
I’m using select2:select event and its triggers everytime when you select new value (that’s obv) but it doesn’t if selecting value is the same. In this example click on option with red border, close alert and then try to select this “red option” again. Event won’t start. How can I trigger it again? I tried use select2:close event but there is a problem. If we click outside select2 event triggers too and it’s not ok for me. I tried attach new event directly on select2 dropdown but it doesn’t work because you blocked it (I used $(document).on('click', '.select2-results__option', function(){});)
Any ideas?
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Comments: 23
Ok, may I present a more hacky solution:
Why this was closed? It’s still the issue in the latest 4.0.12
took a inspiration from @scarabdesign for a issue i had with
$(select).val(null).trigger('change')that would make the text empty and set selected to false but still have the data leading to not being able to select the first option unless i selected another optionthis was the
$(select).select2('data')[0]format that was preventing me from selecting the first valuePosting this because i wasted over 10 hours over multiple days/weeks on this “small” issue .
I’d like to see this changed too. Because the “selecting”, “select”, “unselecting” or “unselect” events are not triggered when clicking an item that is already selected in a non-multiselect Select2 element, it seems impossible to have clickable links/buttons inside Select2 options.
The methods described that allow clickable elements inside Select2 options rely on the fact that the “selecting” or “unselecting” events are triggered and the original event is passed to their handlers. That way you can check if the original event was a click event on one of your clickable elements and handle them accordingly.
An easy fix would be to change this:
To this:
This way the “select”/“selecting” get triggered, even when you click the already selected item in a single-select Select2 element.
Well, it seems that the value of the select element itself is not important to you, right? In other words, you are taking the value you select and using it elsewhere (i mean, why else would you want to choose the same item twice). If that’s true, add this:
.on('select2:close', function (event) { this.value = null })In the link to your example, I was able to use the select2:close to set the value to null and was able to select the item with the red border multiple times. Even if you open the dropdown and click outside, the select2:close event does trigger, but all it’s doing is resetting the selector.