Home >Web Front-end >JS Tutorial >How to Display Only Month and Year in jQuery UI DatePicker?

How to Display Only Month and Year in jQuery UI DatePicker?

Susan Sarandon
Susan SarandonOriginal
2024-11-26 17:09:14359browse

How to Display Only Month and Year in jQuery UI DatePicker?

Displaying Month and Year Only in jQuery UI DatePicker

jQuery UI's DatePicker plugin offers the flexibility to customize its appearance. For scenarios where displaying the full calendar isn't necessary, users may want to show only the month and year.

Solution:

To achieve this, a "hackish" yet functional approach involves programmatically hiding the calendar component and modifying the JavaScript configuration. Here's an example:

<html>
<head>
    <script src="jquery.js"></script>
    <script src="jquery-ui.min.js"></script>
    <link rel="stylesheet" href="jquery-ui.css">
    <script>
        $(function() {
            $('.date-picker').datepicker({
                changeMonth: true,
                changeYear: true,
                showButtonPanel: true,
                dateFormat: 'MM yy',
                onClose: function(dateText, inst) { 
                    $(this).datepicker('setDate', new Date(inst.selectedYear, inst.selectedMonth, 1));
                }
            });
        });
    </script>
    <style>
        .ui-datepicker-calendar {
            display: none;
        }
    </style>
</head>
<body>
    <label for="startDate">Date:</label>
    <input name="startDate">

This approach disables the calendar's visibility while preserving the month and year selection functionality. The onClose event handler adjusts the selected date to the first day of the chosen month and year, ensuring that only the month and year are displayed in the input box.

Enhanced Solutions:

Over time, more refined solutions have emerged, addressing potential drawbacks in the original approach. One such solution involves overriding jQuery UI's _selectDay method to prevent calendar days from being selectable. This approach allows for more robust handling of date input while still providing the desired month and year display.

The above is the detailed content of How to Display Only Month and Year in jQuery UI DatePicker?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn