user1259167
user1259167

Reputation: 447

Highlight a select / dropdown with a class when its open or is has a option other than the initial default selected

Ok, this sounds super simple!! but its driving me crazy and giving me brain fade :)

Say I have a basic select box like:

<select id="test">
    <option value="">--- select ---</option>
    <option value="1">One</option>
    <option value="1">Two</option>
</select>

What I would like is for the "highlight" class to be added to the select during the following states:

  1. The select is in its dropped down / open state
  2. The select has a valid option selected (i.e. One or Two)

But it need's to have the class removed if the select is closed back without a valid selection (i.e. it's changed back to "--- select ---")

Sounds easy!!

I tried this which seemed the obvious way:

$(document).ready(function () {

    $('#test').focus(function () {
        $(this).addClass('highlight');
    })

    $('#test').change(function () {
        if ($(this).val() != '') $(this).addClass('highlight');
        else $(this).removeClass('highlight');
    })
});

But it doesn't quite 100% work but it's close, the problem is if you select something then change it back to "--- select ---" but then you don't loose focus of the drop down and re-click it then it does not add the "highlight" class again.

I have tried many combinations of adding extra events like click but I cannot seem to get it working exactly how I would like. It's almost like I need a "opening" event on the select but obviously that does not exist.

Have I missed something seriously obvious here? as I'm a competent web developer who has spent a couple of hours trying to do this!! haha... But it is pretty late here in NZ so that's my excuse if I have :)

Thanks, Carl

Upvotes: 3

Views: 6819

Answers (1)

The System Restart
The System Restart

Reputation: 2881

$('select').on('focus', function() {
    $(this).addClass('highlight').find('option').css('color', '#000');
}).on('blur', function() {
    $(this).removeClass('highlight');
    if (this.value.length) $(this).addClass('highlight');
}).on('change', function() {
    if (this.value.length) $(this).addClass('highlight');
    else $(this).removeClass('highlight')
});​
​

DEMO

Upvotes: 2

Related Questions