For a vanilla CRM solution I’m building, frequently I need to update SELECT element option lists. For ages, I’ve simply been pasting the methods I used, borrowed heavily from mredkj.com’s select list tutorial, into my various classes.
Finally tiring of that, I wrote a small class that simply lets you add all new options or remove all the options. I haven’t needed anything more substantial than that, since I simply populate and repopulate my SELECT option lists based upon the results of a JSON data stream.
My first instinct was to try to $extend an individual SELECT element with functions to allow for this, but that seemed to be the wrong approach. Since I never create these elements dynamically, I didn’t have any reason to subclass Element with, say, selectElement, to create new SELECT elements with the extra functions. So, I ended up with what’s below. Not being a JavaScript guy by any stretch of the imagination and a mootools novice, I’m sure it has plenty of issues…
You might also notice it’s not 100% complete yet. I’m pondering a github repo for this and a few other things. Or maybe I just need to upload a source file.
Seems to work in Firefix 2.0.0.16 and Opera 9.50.
var updateableSelect = new Class({ Implements: Options, options: { el:null, defaultOption:null }, initialize: function(options) { this.setOptions(options); this.options.el = $(this.options.el); }, buildOptions: function(optionList, selected) { $A(optionList).each(function(option) { try { this.options.el.add(new Option(option.title, option.value), null); } catch(ex) { this.options.el.add(new Option(option.title, option.value)); } if(selected && selected == option.value) { this.options.el.selectedIndex = this.options.el.length-1; } }.bind(this)); }, resetOptions: function(setDefault) { for(var i = this.options.el.length-1; i>=0; i--) { this.options.el.options[i] = null; } if(setDefault) { this.buildOptions([this.options.defaultOption], this.options.defaultOption.value); } }, resetSelection: function() { this.options.el.selectedIndex = null; } });