jQuery How-To: Changing One Dropdown’s Value Based on Another’s, in Every Browser

$("#popup-dates select").change(function() {
        var fromMonth = new Number( $('#month-from').val() );
        var toMonth = new Number( $('#month-to').val() );
        if ( fromMonth > toMonth ) {
                $('#month-to').val($('#month-from').val());
        }
});

I’m working on a project where the visitor searches for info in a date range, selecting a From: month (#month-from) and a To: month (#month-to) within the same year. This code automatically advances #month-to to equal #month-from if the visitor tries to make a selection where #month-to would be earlier than #month-from, creating a reverse timespan (ie. trying to search from June to January within the same year).

The code does the following:

  1. Gets the values of the selected options (January’s option should have value=”1″, February’s “2″, etc.) and converts them to Number variables.
  2. Compares the two values.
  3. Updates #month-to to equal #month-from if one of them is changed to create a reverse timespan.

The most important part to note, though, is using $(“#popup-dates select”).change() as opposed to $(“#popup-dates option”).click(). For some reason the latter, which is semantically more accurate, simply doesn’t work in WebKit browsers like Chrome and Safari. Using $(“#popup-dates select”).change() will work in every browser, even IE6.

Hope this can save someone some time.