1
votes

I am trying to use Jquery to select an option in dropdownlist. if the today date is less than 15 the current month selected true in dropdown list. and if today date is greater than 15 the next month selected true in the dropdown list. (value selected into dropdownlist).

html

         <select class="availDropdown">
            <option value="">Month</option>
            <option value="Jan">Jan</option>
            <option value="Feb">Feb</option>
            <option value="March">March</option>
            <option value="April">April</option>
            <option value="May">May</option>
            <option value="June">June</option>
            <option value="July">July</option>
            <option value="August">August</option>
            <option value="September">September</option>
            <option value="October">October</option>
            <option value="November">November</option>
            <option value="December">December</option>
        </select>
1
Look into the javascript Date() reference with getMonth() function, and use that to determine current month and match it to your dropdown. w3schools.com/jsref/jsref_obj_date.asp - Daniel Sanchez

1 Answers

2
votes

Heres some pure Javascript. All I did was add an id to your selector so I could use document.getElementById(id), since I could't load up jQuery quickly, but the concept is simple and understandable.

// Find the day of the month 
    var day = new Date().getDate();
// Find the month number (+1 since it starts at 0, and 0 is your 'select month' option)
    var month = new Date().getMonth() + 1;
// increase the month number if the day is bigger than 15
    if(day > 15){
        month++;
        if( month > 12 ) month = 1;
    }
// get the select object, list its options and find the one at the months position. 
// Set it to true.
    document
    .getElementById("select")
    .options[month]
    .selected = true;

Edit

Sorry, I used the wrong function. getDay() gets the day of the week, which caused this to happen. Using getDate will return the day of the month (1-31). It works now. I also simplified the code a bit, being DRY and all.