Friday, 23 November 2012

Bootstrap dropdownlist/combo box

Styling some web controls is not possible in the browser since they are drawn by the operating system. One such beast is the combo box a.k.a. the dropdownlist. What we want is the means to select something from a list which is then put into a text box and which can, optionally, allow you to free type something else. Something a bit like this:


It looks quite simple in bootstrap but again, it is hard to make it behave in a way that plays nice with server side code. The way I got it to play was the following:
<div class="dropdown">
            <div class="input-append">
                <input type="text" class="dropdown-toggle input-xlarge" data-toggle="dropdown" id="requiredPackage" runat="server" />
                <span class="add-on dropdown-toggle" data-toggle="dropdown"><i class="icon-chevron-down"></i></span>
                <ul class="dropdown-menu" role="menu" id="packageMenu">
                <li><a href="#" data-value="5">Free (50 users, 100 logins) free</a></li>
                <li><a href="#" data-value="1">Basic (200 users, 1000 logins) £5/month</a></li>
                <li><a href="#" data-value="2">Mid-size (500 users, 5000 logins) £10/month</a></li>
                <li><a href="#" data-value="3">Large (1000 users, 10000 logins) £15/month</a></li>
                <li><a href="#" data-value="4">Enterprise (5000 users, 50000 logins) £25/month</a></li>
            </ul>
            </div>
            
        </div>

I used a plain input with a runat server tag. This might have worked with a standard asp:TextBox but I ended up with this. I then added an asp:HiddenField that would allow me to set something on the client side and then read this on the server side. In fact, I wanted the data-value of the selection rather than the description of the selected item. data- is a way of adding customised attributes which can easily be read by Javascript. In this case, I used jQuery to handle the selection of any of the li items and then put the description into the text box and the value into the hidden field like this:
<script type="text/javascript">
        $(function ()
        {
            $('#packageMenu a').on('click', function (event)
            {
                $('#MainContent_requiredPackage').val($(this).text());
                $('#MainContent_selectedPackage').val($(this).data('value'));
            });
        });
    </script>

A few notes on this. By using jQuery 'on' function, I can apply the handler to a group of elements, in this case all the li elements (the a tags) that live under the packageMenu element. I then put the text of the element into the text box and use jQuery data() function to retrieve data-value and put this into the hidden field. This script is simply put at the bottom of the HTML page and is wired up to jQuery 'ready' function using the standard format.
Post a Comment