bluzky / nice-select2

A lightweight vanilla javascript library that replaces native select elements with customizable dropdowns
https://bluzky.github.io/nice-select2/
MIT License
361 stars 60 forks source link

Ensure all items unselected on change (_onItemClick) #63

Closed rpodsada closed 1 year ago

rpodsada commented 1 year ago

This resolves an issue with the dropdown where the initially selected option on load stays selected even if you choose another item in the list. After selecting the other item, both the original item that was selected on load, and the new item, retain the selected class, and both remain bold. (However, the value of the dropdown is correct. This is primarily a display issue.)

The issue is that this.selectedOptions does not have item.element defined, which is what _onItemClick is trying to deselect. item.element is supposed to be a reference to the li element in the fancy drop-down, but this is only populated in this.options when when the dropdown is rendered (via _renderItem.)

this.selectedOptions is populated separately from extractData, but this method is not aware of the contents of the ul so it doesn't add the item.element reference required.

A simple fix is to is to clear the selected state on this.options as well, to ensure all previously selected options in the original select are unselected. I have left the original clearing of this.selectedOptions as well just to be safe, and ensure nothing is left selected anywhere. This fix resolved the issue on my instance and now works perfectly.