Sunday, February 26, 2012

Using styles for select boxes

Well, select box is one of those elements which cannot be styled reliably with css. The only things explorer supports are to change the background color of the select box and the font-size. The annoying down button and the border cannot be removed in IE. So, it is best not to style a select box for consistency across browsers. Don't worry, there is a work around for the same.

What we need to do is to keep the select box and a span in a div. Then we keep the select box over the span and make the opacity of the select box as 0. Span can be styled reliably and hence will give the user the feel that it is the select box that has been styled. Now, with jquery we need to write events which will populate the span with the values of the select box. The events will be for click and for key up(so that u can select with movement of keys in the keyboard).

Span Click Me

The code:
<div class="container">
<span style="background: none repeat scroll 0% 0% rgb(238, 238, 238);
display: block; width: 100px;">
Click me
</span>
<select id="selBox" style="margin-top: -20px; 
opacity: 0; position: absolute; width: 100px;">
 <option>first option</option> 
 <option value="second option">second option</option>
 <option value="third option">third option</option>
 </select>

</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript">
</script>
<script type="text/javascript">
 $("#selBox").bind({
        "change": function() {
          $(this).prev().text($(this).find(":selected").html());
        },
        "keyup": function(){
          $(this).prev().text($(this).find(":selected").html());
        }
        });
</script>