I have two dropdownlist that hold months and years...
$(document).ready(function () {
$('#Months option:eq(' + (new Date).getMonth() + ')').prop('selected', true);
alert((new Date).getMonth());
$('#Years option:eq(' + (new Date).getFullYear() + ')').prop('selected', true);
alert((new Date).getFullYear());
});
I wrote the JQuery script as above so that when my program runs the dropdown selected value must be the current month and year..
but when i execute the program.. the alert gives 7 and 2012.. but in my view the current month is selected but the current year is not why?? and how can I make my dropdown to select current year??
ready(function () { $('#Months option:eq(' + (new Date). getMonth() + ')'). prop('selected', true); alert((new Date). getMonth()); $('#Years option:eq(' + (new Date).
JavaScript Date getMonth() getMonth() returns the month (0 to 11) of a date.
You can do it like that: var d = new Date(); var month = d. getMonth()+1; var day = d. getDate(); var output = d.
innerHTML = months[date. getMonth()] + ' ' + date. getFullYear(); };
jQuery
var d = new Date(),
n = d.getMonth(),
y = d.getFullYear();
$('#months option:eq('+n+')').prop('selected', true);
$('#years option[value="'+y+'"]').prop('selected', true);
HTML
<select id="months">
<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="years">
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
</select>
DEMO
Months are returned as an integer from 0 (January) to 11 (December): see http://www.java2s.com/Tutorial/JavaScript/0240__Date/DategetMonth.htm
So the current month (August) would return 7. To be able to match up with the usual month index (meaning 1 to 12), use ((new Date()).getMonth() + 1)
.
As pointed out in the comments, I misunderstood the problem. The month is correct because of the zero-based array for months and the jquery selector :eq()
being also zero-based.
However as pointed in other answers, the year returned would not match :eq()
which matches the nth element in the jquery selector. Using as suggested option[value=' + (new Date).getFullYear() + ')'
would be better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With