Question

I am trying to do a month year drop down that takes the HTML and removes previous months if the current year is selected. All works ok but it always sets the month option focus to the last one in the object, have tried focus, selected with no joy.

http://jsfiddle.net/FneGp/

var selectList = $("select#months");
    var selectListOptions = $("select#months option");

    var d = new Date(),
        n = d.getMonth(),
        y = d.getFullYear();
    $("select#years").on("change", function (){
        if ($(this).val() == y) {
            $("select#months").children("option").each(function () {
                if ($(this).val() <= n) {
                    $(this).remove();
                }
            });

        }
        else {
            selectListOptions.appendTo(selectList);
        }
    });

I have set up a fiddle to show the problem.

Any help gratefully appreciated

Thanks in advance

Richard

Was it helpful?

Solution

One simple solution I would suggest is to change the select as mentioned below

<select id="months">       
        <option value="1">January</option>
        <option value="2">February</option>
        <option value="3">March</option>
        <option value="4">April</option>
        <option value="5">May</option>
        <option value="6">June</option>
        <option value="7">July</option>
        <option value="8">August</option>
        <option value="9">September</option>
        <option value="10">October</option>
        <option value="11">November</option>
        <option value="12">December</option>
     <option selected="selected">Month</option>
</select>

because when appending the last option is getting selected by jQuery.

EDIT:

Change your else statement as below

else {
            selectListOptions.appendTo(selectList);
            $('#months option:contains("Month")').prop('selected', true);
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top