Bootstrap Datepickers

Here is a quick code snippet that I wrote today. It relates to initiating a Bootstrap datepicker control when specific elements are clicked.

Bootstrap have some very nice input addons that you can use to give your form elements some context. Adding a $ sign before the input field means you don’t have to format the input text as currency because the UI shows the user what type of content is required. Similarly, there is a calendar addon that works nicely with a datepicker. But the Bootstrap datepicker is “bound” to an input field which means that the datepicker is initiated on focus of that input field.

I think it is a better user experience if the input addon ALSO initiated the datepicker.

Firstly, let’s look at the HTML.

<div class="form-group">
	<label class="control-label col-md-2" for="DatePaid">Date Paid</label>
	<div class="col-md-2">
		<div class="input-group date">
			<input class="form-control" data-val="true" data-val-date="The field Date Paid must be a date." 
				id="DatePaid" name="DatePaid" type="text" value="">
			<span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
		</div>
	</div>
</div>

So we have a simple form group with an input that we will use for our datepicker.

Here is the javascript that will turn the input into a datepicker.

<script src="~/Scripts/Moment/moment-with-locales.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>

<script>
	$(function () {
		$(".input-group.date input").datetimepicker({
			defaultDate: "",
			format: "DD-MMM-YYYY"
		});
	});
</script>

So what will happen is when the input receives the focus, the datepicker control will be initiated. But wouldn’t it be good if the icon next to the input also initiated the datepicker?

Here is some javascript code that does that.

<script src="~/Scripts/Moment/moment-with-locales.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>

<script>
	$(function () {
		$(".input-group.date input").datetimepicker({
			defaultDate: "",
			format: "DD-MMM-YYYY"
		});
		
		//	Added so that the addon also initiates the datepicker
		$(".input-group.date .input-group-addon").on("click", function () {
			$(this).prev().trigger("focus");
		});		
	});
</script>

Now, when the user clicks the input field (or tabs into it) OR when the user clicks the Bootstrap addon next to the input, the datepicker will be initiated.

Til next time …


Leave a Reply

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