Make Dijit’s FilteringSelect Widget Display an Empty Option Value Label
I was recently working with the FilteringSelect Dojo Dijit widget and realized that when the first OPTION in the SELECT widget had a label with an empty value (like "Choose one..." or "Select you state"), the label wasn't displaying. That's no good! What I did was monkey patch the widget's prototype to make sure that label was displaying when it was loaded.
The Dojo JavaScript
/* Modify ComboBox and FilteringSelect to use default label if value is "" */ (function(){ var oldPMIP = dijit.form.FilteringSelect.prototype.postMixInProperties; dijit.form.FilteringSelect.prototype.postMixInProperties = function(){ if(!this.store && this.srcNodeRef.value == ''){ var srcNodeRef = this.srcNodeRef, nodes = dojo.query("> option[value='']", srcNodeRef); if(nodes.length){ this.displayedValue = dojo.trim(nodes[0].innerHTML); } } oldPMIP.apply(this,arguments); }; })();
Like my previous monkey patching tutorial, we're essentially modifying the prototype of the Dojo Dijit (FilteringSelect, in this case) we'd like to act differently. In this case, however, we're going to "save" the original prototype so that we may trigger its original functionality after we change a few settings first. In this case, we want to ensure that the displayedValue of the FilteringSelect is the blank option's label. After all, empty first labels are ugly, right?
Prototype modification is super useful, isn't it? Now every FilteringSelect will be fixed by changing this one method on the prototype. Hmmm...prototype modification sounds very familiar to me....