Monday, July 7, 2014

jQuery UI: Selectmenu Placeholder Text

Input elements have a placeholder attribute, which does a decent job at telling the user exactly what's expected. What I really like about using this attribute is that there's no additional space required — it appears inside the widget, when there's no text. Hence the name. So, I tried to do something similar with the jQuery UI selectmenu widget.

By default, the selectmenu displays the text of the selected option, which makes sense, since this is how you know which option is selected. What about when the widget is first created? If there's no option selected, that's when I want to display the placeholder text for the selectmenu. So the first step is figuring out when there's nothing selected — which is actually trickier than it sounds. With the :selected pseudo-selector, there's always a selected option. Implicitly, it's the first option — if there's no selected attribute specified on any of the options.

This is exactly what we're after — we want to display the placeholder text if the select markup doesn't explicitly have a selected attribute in any of it's options. Here's an example of how to override the default implementation of the selectmenu to add a placeholder option.

$.widget( 'app.selectmenu', $.ui.selectmenu, {
    _drawButton: function() {
        this._super();
        
        var selected = this.element
                .find( '[selected]' )
                .length,
            placeholder = this.options.placeholder;
        
        if ( !selected && placeholder ) {
            this.buttonText.text( placeholder );    
        }
    }
});

$( '[name="speed"]' ).selectmenu({
    placeholder: 'Select a speed'
});

And here's what the resulting selectmenu looks like before an option is selected.

No comments :

Post a Comment