How to set default SELECT OPTION using jQuery/JavaScript

I recently needed to set a default option for a SELECT drop down list. As you probably already know, select elements do not support a default value, but you can use jQuery to set a default value after the page has loaded.

To make things even more complicated, I had three forms each with their unique requirements – one needed the default value to be the current year, another the next year and another the current financial year.

I also needed to select the default field by the option’s text – not it’s value.

I came up with the following script, a combination of jQuery and JavaScript.

If your page does not already include jQuery, don’t forget to add it to the header.

If you’re using this code on a WordPress website, you already have jQuery available but need change the $’s to jQuery.

Note: getMonth() returns January as 0, February as 1, and so on.

    $( document ).ready(function() {
        var currentMonth = (new Date).getMonth();  // GET current month
        var currentYear = (new Date).getFullYear();  // GET current year
        var lastYear = currentYear - 1;  // CALCULATE last year
        var nextYear = currentYear + 1;  // CALCULATE next year
        if (currentMonth <= 5) {   // IF current month is June (5) or earlier use financial year pattern 2014/2015
            financialYear =  lastYear+"/"+currentYear;
        } else {   // ELSE current month is after June (5) use financial year pattern 2015/2016
            financialYear = currentYear+"/"+nextYear;
        }
        // TARGET form action with a select option, look for value that equals currentYear/nextYear/financialYear and set selected property to true
        $('form[action="form_action_currentYear.asp"] select option').filter(function () { return $(this).html() == currentYear; }).prop('selected',true);
        $('form[action="form_action_nextYear.asp"] select option').filter(function () { return $(this).html() == nextYear; }).prop('selected',true);
        $('form[action="form_action_financialYear.asp"] select option').filter(function () { return $(this).html() == financialYear; }).prop('selected',true);
    });

Was this article helpful?

Related Articles