Here’s a demo, followed by the code used to generate it (the default selects are for UI comparison):
Notice how SelectMultiple will automagically pass the onChange event to your observer function. Also, notice the striking similarity to Chosen. I shamelessly “borrowed” their UI and tweaked it a little to look more natural alongside native widgets. My thanks to them for at least making something visually appealing.
Documentation for the optional parameters is available at the top of selectMultiple.js, and all optional parameters are used in this example.
It’s On Github, Right?
Yes! Although not in its own project… You can pick up the source, CSS file (chosen.css), and image file (chosen-sprite.png) here. Problem solved!
“Why all the hating?” you ask. Let me explain. According to the W3C, option tags ought to support onclick. The only browser to actually support this behavior? Firefox. And love or hate it, you can’t only support Firefox. So any clever UI tricks you want to do with hover on select options? Nope, not for you. All right, one complaint, that’s not so bad. But what if you want to use select multiple? What? Oh yeah, I forgot about that… Yeah, you and the rest of the world. Nobody uses them because the UI sucks and they’re a pain to implement. The onchange event doesn’t tell you anything about all the elements that are selected, just the element the user last clicked on. You’re left to traverse the options and find out yourself. So, you use a nice new fangled library like Chosen, which is a nice try at solving the UI problem, while addressing exactly -1 technical issues. Yep, it introduces 1, but I’m getting ahead of myself. So, the UI is great, and oh look! They fire their own special onchange event! And they support select multiple! They probably let me know about all the currently selected… no? Or which option just got removed? Still no? Man, that sucks. But it’s implemented with DIV layers! We could use onhover with these … oh, there’s no API for that? And since they’re being created and destroyed dynamically with no event information fired, it’s impossible to dynamically add this functionality ourselves? Well, that’s a missed opportunity… but it’s at least a prettier UI! Oh wait, but I need to show my users the disabled options in this list, and Chosen “kindly” hides them from the user. But there’s an option to change that, right? That’s where you would be wrong, and we’ve arrived at -1 features. And CSS won’t help you, you have to actually prevent these options from entering the selected list for it to really count as disabled from a UX perspective. So there you go. JS events on option tags, UI fail, which multiple values?, and no tools to save us. Well, not until today…