In some case, we may not need to show date from datepicker, we might need only month,year part, so in n this article, I have provided example to show only month and year in bootstrap datepicker with code demo, it works with Bootstrap 3, 4 and 5
Let's consider we have the below HTML code, in which we will be showing bootstrap datepicker without date part, and show only month/year part.
<input type="text" class="form-control" name="datepicker" id="datepicker" />
then the jQuery code using Bootstrap datepicker would be
$("#datepicker").datepicker( {
format: "mm-yyyy",
startView: "months",
minViewMode: "months"
});
As you can see in the above jQuery code, we have added property "format: "mm-yyyy"", which makes us to show month and year format to user and using "startView:"months"
", we are showing months-years only.
Note: From version 1.2 and above viewMode is changed to startView, for older versions use viewMode instead of startview in the above JS code.
Complete code including all the required JS/CSS files
<link href="https://netdna.bootstrapcdn.com/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.2.0/css/datepicker.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://netdna.bootstrapcdn.com/bootstrap/2.3.2/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.2.0/js/bootstrap-datepicker.min.js"></script>
<br/>
<input type="text" class="form-control" name="datepicker" id="datepicker" />
Output:
Change month event in Bootstrap datepicker
Now, as we are showing only month and year in datepicker, you might need to do some work while datepicker month is changed, so here is the code to call jQuery code on changing month
var dp=$("#datepicker").datepicker( {
format: "mm-yyyy",
startView: "months",
minViewMode: "months"
});
dp.on('changeMonth', function (e) {
//do something here
alert("Month changed");
});
Here is the fiddle sample
Similarly, you can call event on "changeYear" also, which will have code even call code as below
//changeYear event trigger's
dp.on('changeYear', function (e) {
//do something here
alert("Year changed ");
});
That's it, hope it helps, if you have any questions, feel free to ask in comment sections below.
You may also like to read:
vikas_jk
You need to use 'autoclose:true' property, as shown here
https://qawithexperts.com/questions/467/how-to-auto-hide-bootstrap-date-picker-after-selecting-date
Here is the fiddle demo: https://jsfiddle.net/nqy9bhj0/
Thanks.
Edited at :- 10/12/2022 7:31:03 AM