Change CSS dropdown on click or hover?

Inspired by StackOverflow question ... I tried something and I added a gray background to the disabled selection.

The problem is that when I click on any selection (which radio button is off) the background of the dropdown remains grayed out.

How can I get it back to normal (white) when pressed, even if the radio button is unchecked?

You can see it here http://jsbin.com/okuca/

Here is my actual code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test </title>
<style type="text/css">
  label.disabled select { opacity: 0.5; filter: alpha(opacity=50); background-color:#CCC; }

</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript">
  $(function() {
    $('div.formdiv').bind('click',function() {
      $('label.disabled',this).removeClass('disabled');
      $('input:radio',this).attr('checked',true);
      $('div.formdiv').not(this).find('label').addClass('disabled').find('select').attr('selectedIndex',0);
    }).find('label').addClass('disabled');
  });
</script>
</head>

<body>

<div class="formdiv">
  <label for="Name">
    <input id="Name" name="radio1" type="radio" />Name:
    <select name="select1">
      <option value="Rose">Rose</option>
      <option value="Lily">Lily</option>
    </select>
    </br>
  </label> 
</div>

<div class="formdiv">
  <label  for="Colours">
  <input id="Colours" name="radio1" type="radio" />Colour: 
  <select name="select2">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
  </select>
    </label> 
  </br>
 </div> 

<div class="formdiv">  
 <label  for="Sport">
  <input id="Sport" name="radio1" type="radio" />Sport: 
  <select name="select3">
    <option value="Tennis">Tennis</option>
    <option value="Cricket">Cricket</option>
  </select>
  </label> 
  </br>
</div>
  </body>
</html>

      

You can edit it here: http://jsbin.com/okuca/edit

+1


a source to share


1 answer


The problem is that the click handler doesn't fire until you release the mouse button (and the dropdown disappears), so the style label.disabled select

is still being applied.

There are two ways to fix this. First, you can add another CSS rule for :focus

that overrides the styled style:

label.disabled select:focus { opacity: 1.0; filter: alpha(opacity=100); background-color:white; }

      



However, this can get you in trouble if your styles get more confusing. Instead, I would recommend changing your click handler to a mousedown handler:

$('div.formdiv').bind('mousedown',function() {

      

This causes the handler to run (and the class to be removed) before the dropdown appears.

+4


a source







All Articles