Link to home
Start Free TrialLog in
Avatar of skij
skijFlag for Canada

asked on

jQuery: add a class to ALL options with selected value

Using jQuery, how can I add a class to ALL options that have the selected value?

<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<style>
option.sel {
background: red;
}
</style>
<script type="text/javascript">

$(document).ready(function () {
  $('#s').change(function () {
    $('#s option').removeClass('sel');
    $('#s option:selected').addClass('sel');
  });
});

</script>
</head>
<body>

 <select id="s">
  <option>SELECT</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="1">One</option>
  <option value="2">Two</option>
  <option value="3">Three</option>
 </select>

</body>
</html>

Open in new window

SOLUTION
Avatar of Prakash Samariya
Prakash Samariya
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Working sample http://jsbin.com/xulaliwipu/1/edit?html,output

Once you select an option, then select again, your previous selection is in red.  Will not work in chrome/mac.
Avatar of skij

ASKER

When "1" is selected, ALL options with a value of "1" should be selected.
@Scott - not necessary to add the select the id identifies uniquely identifies the value.

The code you have posted works - not sure what the issue is.

One thing to note however the nature of a select box is that the selected item is highlighted when you drop the box down - this will mask any styling that you have applied to the option - once you move the mouse over another of the option the highlighting will become visible.

Are you asking how to change the highlight colour?
Avatar of skij

ASKER

With the code I posted, when "1" is selected, the background of "1" turns red.

Instead, when "1" is selected, I want the background of both "1" and" "One" to turn red, because both of them have:
value="1"
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just comment your line as below
 //$('#s option:selected').addClass('sel');

Open in new window

and add line as below
$('#s option[value=' + $('#s').val() + ']').addClass('sel');

Open in new window