Categories
JavaScript Answers

How to Add a Month Picker with JavaScript?

Spread the love

Sometimes, we want to add a month picker with JavaScript.

In this article, we’ll look at how to add a month picker with JavaScript.

Add a Month Picker with JavaScript

To add a month picker with JavaScript, we can use the jQuery UI date picker library.

For instance, we can write:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>

<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>

<link rel="stylesheet" type="text/css" media="screen" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">

<input name="startDate" id="startDate" class="date-picker" />

to add the script and link tags for jQuery and jQuery UI.

And we also add the input element for the date picker.

Then we write:

$('.date-picker').datepicker({
  changeMonth: true,
  changeYear: true,
  showButtonPanel: true,
  dateFormat: 'MM yy',
  onClose(dateText, inst) {
    const month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
    const year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
    $(this).datepicker('setDate', new Date(year, month, 1));
  }
});

to select the input with:

$('.date-picker')

And we call datepicker with an object to turn the input into a date picker.

changeMonth lets us change the month if it’s true .

changeYear lets us change the year if it’s true .

showButtonPanel shows the bottom button panel if it’s true .

dateFormat lets us set the date that’s returned by the dateText parameter.

onClose is run when we close the date picker.

In the method, we get the month and year from the top dropdowns, and we call datepicker with 'setDate' to set the date.

Conclusion

To add a month picker with JavaScript, we can use the jQuery UI date picker library.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *