skij
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>
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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?
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?
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"
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Just comment your line as below
//$('#s option:selected').addClass('sel');
and add line as below$('#s option[value=' + $('#s').val() + ']').addClass('sel');
Once you select an option, then select again, your previous selection is in red. Will not work in chrome/mac.