JavaScript Week Picker

One of the new input types in HTML5 is week which allows you to specify a week period. Unfortunately although Chrome brings up a nice datepicker to allow you to select the week Firefox and IE12 and earlier don’t implement this and so just display a standard input text box.

In order to create an equivalent of the Chrome week picker I used bootstrap-datepicker and updated the CSS and events for it to allow it to select weeks.

The below code was part of a .NET Core MVC project, hence the embedded C#.

References are needed to the relevant CSS and js files for JavaScript, Bootstrap and bootstrap-datepicker.

HTML


@{
    DateTimeFormatInfo dateTimeFormatInfo = DateTimeFormatInfo.CurrentInfo;
    Calendar calendar = dateTimeFormatInfo.Calendar;
    string week = TempData["Week"].ToString();
}

<div class="row">
    <div class="col-lg-2">
        <input type="week" value="@week" class="form-control" id="Week" />
    </div>
</div>

CSS


/* Week picker */
.datepicker-days > table > tbody > tr:hover {
    background-color: #808080;
}

JavaScript


$(document).ready(function () {
	// Add weekpicker
	if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Trident") != -1) {
		$('#Week').datepicker({
			calendarWeeks: true,
			weekStart: 1
		});
	};
});

$('#Week').on('changeDate', function (e) {
	var value = $("#Week").val();
	var year = moment().format('YYYY');
	var week = moment(e.date).format('WW');
	$("#Week").val(year + '-W' + week);
});

Leave a Reply

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