In one of our previous article, we have provide working sample to show only month and year in bootstrap datepicker, but in this article, I will provide working example to show only Year part in datepicker, it can be useful when you want user to select only Year in bootstrap datepicker.
Let's consider we have the below HTML code, in which we will be showing bootstrap datepicker without date part, and show only year part.
<input type="text" class="form-control" name="datepicker" id="datepicker" />
then the jQuery code using Bootstrap datepicker for selecting only years would be
$("#datepicker").datepicker({
format: "yyyy",
viewMode: "years",
minViewMode: "years",
autoclose:true //to close picker once year is selected
});
As you can see in the above code, we have provided 'format:"yyyy"
' (ex: 2022) and "viewMode:'years
'", which will allow datepicker to show/select only year part and it will hide Months or date part, plus we have made 'autoclose:true', which will close datepicker as soon as we select year.
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 JS/HTML code would look like this
<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" />
<script>
$(document).ready(function(){
$("#datepicker").datepicker({
format: "yyyy",
viewMode: "years",
minViewMode: "years",
autoclose:true
});
})
</script>
Here is the working fiddle example
Change Year event call in Bootstrap datepicker
Once you have used above code to select years correctly, you may want to call other functions or want to do more with year selected, once it is selected by user.
So here is the event, which will be called once Year is selected
var dp= $("#datepicker").datepicker({
format: "yyyy",
viewMode: "years",
minViewMode: "years",
autoclose:true
});
//changeYear event trigger's
dp.on('changeYear', function (e) {
//do something here
alert("Year changed ");
});
Here is the complete fiddle example to test this.
That's it, hope this helps in creating input field with only year select in bootstrap datetimepicker.
You may also like to read:
Creating bootstrap switch button (Easy way)
How to create social media share buttons using HTML & JavaScript? (no external library)