Make Dijit’s FilteringSelect Widget Display an Empty Option Value Label

By  on  

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....

Recent Features

Incredible Demos

  • By
    CSS Transforms

    CSS has become more and more powerful over the past few years and CSS transforms are a prime example. CSS transforms allow for sophisticated, powerful transformations of HTML elements.  One or more transformations can be applied to a given element and transforms can even be animated...

  • By
    MooTools CountDown Plugin

    There are numerous websites around the internet, RapidShare for example, that make you wait an allotted amount of time before presenting you with your reward. Using MooTools, I've created a CountDown plugin that allows you to easily implement a similar system. The MooTools JavaScript The CountDown class...

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!