Search code examples
javascripthtmldrop-down-menu

Month selection dropdown in HTML and JavaScript


I have 2 drop downs in HTML both representing months. So I want a validation like following.

If I select the first drop down month as April, then the next drop-down menu should start from the month April. If the first one is changed to June then the second should change to June.

<div id="head2" style="width:15%;float:right;margin-left:5px;">
    <select id='gMonth2' onchange="show_month()">
    <option value=''>--Select Month--</option>
    <option selected 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>
    </select> 
    </div>
    
<div id="head1" style="width:15%;float:right;margin-left:5px;">
        <select id='gMonth1'>
    <option value=''>--Select Month--</option>
    <option selected 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>
    </select> 
    </div> 

The function will be:

function show_month()
{
// Comments
}

How should I write that function?


Solution

  • Easy with jQuery:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js" type="text/javascript"></script>
    
    <script>
    $(function(){
      $('#gMonth2').change(function(){
        var month = $(this).val();
        $('#gMonth1').val(month);
      });
     });
     </script>
    

    and skip the onChange event in the first select...

    Working example here: http://jsfiddle.net/sCnEZ/1/