Monday, September 14, 2009

How to disable HTML Select Option in IE

One of the project I was working had a requirement to disable one or more of the option element in a select field. A fairly straight forward use case, normally you can just write ‘disabled’, but to be valid XHTML, you need the disabled=’disabled’ variant. The point is, this works fine and looks great in Firefox. The options are not selectable and are nicely grayed out.

<select name="range">

    <option value="1" disabled="disabled">option1</option>

    <option value="2">option2</option>

    <option value="3">option3</option>

    <option value="4" disabled="disabled">option4</option>

</select>

But the problem I found was with IE. It totally refuses to understand this and whats interesting is that its the problem with IE6 & IE7, IE8 has come up with updates.




Solution

One of the main solution that is suggested is using JavaScript. Traverse through the DOM and pick the option having attribute disabled and apply the gray color and change the focus when mouse over. Sounds good but what happens when JavaScript is turned off. So this solution wont work in all cases. So we need some kind of work around on this and interestingly HTML comes again for the rescue. There is an element in HTML called the optgroup which allows you to group similar items in a select box. Using this we can emulate the so called disabled property. The code is as follows

optgroup{ color:#ccc; font-weight:normal; font-style:normal; }

<select name="range">

    <optgroup label="option1"></optgroup>

    <option value="2">option2</option>

    <option value="3">option3</option>

    <optgroup label="option4"></optgroup>

</select>



You can see that the optgroup is used to emulate the disabled property and the gray out is done using CSS. Any one facing the IE disabled problem can use this as a work around. Comments and faq are most welcome.

4 comments:

  1. This is indeed very useful in case of writing browser compatible script!

    ReplyDelete
  2. Three are usually cheap Ralph Lauren available for sale each and every time you wish to buy. Flat for sale Slough

    ReplyDelete
  3. Excellent Blog! I would like to thank for the efforts you have made in writing this post. I am hoping the same best work from you in the future as well. I wanted to thank you for this websites! Thanks for sharing. Great websites! apartments for sale near me

    ReplyDelete