Month selection dropdown in HTML and JavaScript

2019-04-21 07:09发布

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'>Janaury</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'>Janaury</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()
{
//
}

How should I write that function?

2条回答
乱世女痞
2楼-- · 2019-04-21 07:48

Your JS function could be like this:

function show_month(obj) {
    document.getElementById('gMonth1').selectedIndex = obj.selectedIndex;
}

You should change onchange="show_month()" with onchange="show_month(this)"

Check out this jsfiddle

查看更多
The star\"
3楼-- · 2019-04-21 08:08

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/

查看更多
登录 后发表回答