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

  • By
    fetch API

    One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest, wasn't really made for what we've been using it for.  We've done well to create elegant APIs around XHR but we know we can do better.  Our effort to...

  • By
    Create a CSS Flipping Animation

    CSS animations are a lot of fun; the beauty of them is that through many simple properties, you can create anything from an elegant fade in to a WTF-Pixar-would-be-proud effect. One CSS effect somewhere in between is the CSS flip effect, whereby there's...

Incredible Demos

Discussion

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