0

Here's what I want but when I searched the net no answer came up which eventually saddens me. Now here's what I want to happen

I have a drop down which populates the months. What I want is whenever I pick 1 month in month dropdown, I want the other drop down which I will cal period drop down to populate (1,2,3,4) if the picked month in month drop down has 4 weeks and (1,2,3,4,5) if the picked month has 5 weeks.

I don't know where to start and totally have no idea.

Thanks for the help in advance.

Dodgeball
  • 125
  • 2
  • 14

1 Answers1

1

You need to first create two select boxes as shown below:

<select id="month">
    <option>Select Month</option>
    <option value="1">January</option>
    <option value="2">February</option>
    <option value="3">March</option>
<select>
<select id="weeks" style="display:none;"></select>

In your Jquery code you need to get selected value of your month dropdown then use function weekCount to count weeks in a given month with respect to given year. and then simply populate the options in another dropdown.

function weekCount(year, month_number) {

    // month_number is in the range 1..12

    var firstOfMonth = new Date(year, month_number-1, 1);
    var lastOfMonth = new Date(year, month_number, 0);

    var used = firstOfMonth.getDay() + lastOfMonth.getDate();

    return Math.ceil( used / 7);
}
$('#month').change(function(){
    var selectedMonth = $(this).val();
    if(selectedMonth != "") {
        var totalWeeks = weekCount(2014, selectedMonth),
            optionsHtml = '';
        for(var i=1; i<=totalWeeks; i++) {
            optionsHtml += '<option>' + i + '</option>';   
        }
        $('#weeks').html(optionsHtml);
        $('#weeks').show();
    } else {
     $('#weeks').hide();   
    }
});

DEMO

Rupali
  • 1,068
  • 1
  • 12
  • 18
  • What If I want to concatenate something in the result `optionsHtml += '';` like for example I want to concatenate 1st letter of the month – Dodgeball Aug 14 '14 at 10:46
  • Get the first letter from the selected option: `firstLetter =$(this).find('option:selected').text().substring(0, 1)` and append it into the loop like this: optionsHtml += ''; [fiddle](http://jsfiddle.net/srupali/8cywttvz/3/) – Rupali Aug 14 '14 at 11:02