Reputation: 13
I have 10 dropdown lists (views exposed filters in Drupal 7 with AJAX mode enabled) and need to add the extra class "test" to each list if it has default option selected. And delete the class "test" from the lists where default option is not selected. I have:
$('.selDiv option:eq(0)').prop('selected', true).jQuery("select").addClass("test");
It adds the "test" class to all the dropdown lists. But if you have chosen any not default value in any list the "test" classes of all lists (even where default option is selected) disappeared and never appeared again until page reload.
Upvotes: 1
Views: 1707
Reputation: 337560
To achieve this you just need to add a change
event handler to the select
elements which checks the index of the chosen option
and then adds or removes the test
class as needed:
$('.selDiv option:eq(0)').prop('selected', true)
$("select").addClass("test").on('change', function() {
var optionIndex = $(this).find('option:selected').index();
$(this).toggleClass('test', optionIndex == 0);
});
.test {
border: 1px solid #C00;
outline: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="selDiv">
<option>Please select</option>
<option>Foo</option>
<option>Bar</option>
</select>
<select class="selDiv">
<option>Please select</option>
<option>Foo</option>
<option>Bar</option>
</select>
Upvotes: 1