Introduction:
In this Article I will explain how to show jQuery UI date picker with Month Year dropdown Options. In this example I will show only month and year, but we can also show date.
Write
following code to show only month and year dropdowns in date picker:
<script type="text/javascript">
$(function
() {
$('#datepicker').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'MM yy',
onClose: function
(dateText, inst) {
var
month = $("#ui-datepicker-div
.ui-datepicker-month :selected").val();
var
year = $("#ui-datepicker-div
.ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new
Date(year, month, 1));
},
beforeShow: function (input, inst) {
if
((datestr = $(this).val()).length > 0) {
year =
datestr.substring(datestr.length - 4, datestr.length);
month =
jQuery.inArray(datestr.substring(0, datestr.length - 5), $(this).datepicker('option',
'monthNames'));
$(this).datepicker('option', 'defaultDate',
new Date(year, month, 1));
$(this).datepicker('setDate', new
Date(year, month, 1));
}
}
});
});
</script>
Full Source Code for sample application:
<html xmlns="http://www.w3.org/1999/xhtml"
xml:lang="en" lang="en">
<head>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css"
/>
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function
() {
$('#datepicker').datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'MM yy',
onClose: function
(dateText, inst) {
var
month = $("#ui-datepicker-div
.ui-datepicker-month :selected").val();
var
year = $("#ui-datepicker-div
.ui-datepicker-year :selected").val();
$(this).datepicker('setDate', new
Date(year, month, 1));
},
beforeShow: function (input, inst) {
if
((datestr = $(this).val()).length > 0) {
year =
datestr.substring(datestr.length - 4, datestr.length);
month =
jQuery.inArray(datestr.substring(0, datestr.length - 5), $(this).datepicker('option',
'monthNames'));
$(this).datepicker('option', 'defaultDate',
new Date(year, month, 1));
$(this).datepicker('setDate', new
Date(year, month, 1));
}
}
});
});
</script>
<style>
.ui-datepicker-calendar {
display: none;
}
</style>
</head>
<body>
<fieldset style="width:340px; height:90px">
<legend><strong>jQuery:Select
Months & years From Datepicker</strong></legend>
<p>Date: <input type="text" id="datepicker" /></p></fieldset>
</body>
</html>
0 comments:
Post a Comment