1

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 Commented Aug 20, 2014 at 16:14

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

not working sir, they only select current month if i change the date in our system to less than 15
@somethinghere what would happen if it is December 16? Would it still know that January is next?
@RicardoAndres True, it would select the wrong one. Easy fix though.
@somethinghere I found a possible solution: stackoverflow.com/questions/8377498/…
@RicardoAndres if( month > 12 ) month = 1; does the trick as well. Its easy to clamp numbers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.