Kevin Foley
Kevin Foley

Reputation: 119

jquery - change background color of select options when clicked

I have this html code

<p> 
  <label for="contact">Contact name<span class="required"> *</span></label>
  <select name="contact" id="contact" onClick="clearSelect(this,'contact')">
  <option value="">Select Contact</option>
  <?php foreach ($contacts as $contact): ?>
<option value="<?php htmlout($contact['id']); ?>" 
    <?php if ($contact['id'] == $contactID) echo ' selected="selected"';                                
    ?>><?php htmlout($contact['name']); ?></option>
  <?php endforeach; ?>
  </select>    
 </p> 

and this jQuery function

function clearSelect(thisfield, id) {

$j("#" + id).css("background-color","#FFF");
$j("#" + id).css("border","1px solid #CCCCCC");
$j("#" + id).css("color","#000000");
}

When I click the select book the background of the select box changes to white but the drop down list stays the same color until you scroll down it.

Any ideas how to change all the option background colors to white when the select box is clicked?

Upvotes: 3

Views: 3866

Answers (2)

Kevin Foley
Kevin Foley

Reputation: 119

i dont want a border on each of the options in the select box so i changed the function to this

function clearSelect(thisfield, id) {
$j("#" + id).children().andSelf().css({"background-color":"#FFF", 
    "border":"1px solid #CCCCCC",
    "color":"#000000"});
$j("#" + id).children().css({
    "border":"0px solid #CCCCCC"
    });
}

How come this doesnt work again?? when i click the select box now the options menu appears but the background color only changes when i hover over each of them. This is very strange.

Upvotes: 1

DarkAjax
DarkAjax

Reputation: 16223

You may want to use the .css() method combined with .children() and .andSelf() (so it affects the select and the options):

function clearSelect(thisfield, id) {
    $j("#" + id).children().andSelf().css({"background-color":"#FFF", 
        "border":"1px solid #CCCCCC",
        "color":"#000000"});
}

Also, there's no need to call the .css() method multiple times, you can do it a single time with a map of the property-value sets...

Upvotes: 2

Related Questions