Reputation: 81
I have coded the following in order to preset the number of days for each selected month of a form drop-down list. This also tests for leap year (from year 2000+ since I do not require any earlier). This code appears to work correctly for me, but is there a more efficient way of doing this in terms of less code?
<script>
function is_leap()
{
var year=document.getElementById('f_year').value;
var a = 2000;
for(a;a<year;a+=4)
{
}
if(a==year)
{
return true;
}
else return false;
}
function out_days(v)
{
var html = '';
for(var x=1;x<=v;x++)
{
html += '<option value="' + x + '">' + x + '</option>';
}
document.getElementById('f_day').innerHTML=html;
}
function chk_mon()
{
var e = document.getElementById('f_month').selectedIndex;
switch(e)
{
case 0: case 2: case 4: case 6: case 7: case 9: case 11:
{
out_days(31);
break;
}
case 1:
{
if(is_leap())
{
out_days(29);
}
else out_days(28);
break;
}
case 3: case 5: case 8: case 10:
{
out_days(30);
break;
}
default:
{
out_days(31);
break;
}
}
}
</script>
<form action="index.php" method="post" name="form">
Date:<select onchange="chk_mon()" id="f_month" name="from_month">
<option 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>
<select id="f_day" name="from_day">
<script>
chk_mon();
</script>
</select>
<select onchange="chk_mon()" id ="f_year" name="from_year">
<option value="2013">2013</option>
<option value="2014">2014</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
<option value="2019">2019</option>
<option value="2020">2020</option>
<option value="2021">2021</option>
<option value="2022">2022</option>
<option value="2023">2023</option>
<option value="2024">2024</option>
<option value="2025">2025</option>
<option value="2026">2026</option>
<option value="2027">2027</option>
<option value="2028">2028</option>
<option value="2029">2029</option>
<option value="2030">2030</option>
</select>
</form>
Upvotes: 0
Views: 809
Reputation: 121
You could also try JQuery's DatePicker, which is very clean. This example is actually from JQuery's website http://jqueryui.com/datepicker/:
//JQuery and JQuery UI CDNs - Place in <head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
//JS Fn - Place in <head>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
//Put this in the <body>
<p>Date: <input type="text" id="datepicker" /></p>
Upvotes: 2