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);
});
2 Comments
Simon Gutgesell · 10th May 2018 at 4:13 pm
Hello!
I am a student at a Swedish highschool, and I am developing an alternative schedule viewer since the school’s viewer is not really that practical. I earlier used Chrome’s default datepicker but since many other students use Safari (we got MacBooks from our highschool) I would like to use a more controversial datepicker. The thing is that the schedule generator can generate both week schedules and day schedules, and I made it so that the website uses the type of schedule that suits the window ratio of the webpage the best. Which leads me to my problem, I used the bootstrap-datepicker –which your cover fortunately is based on– for the day schedule. The only problem with it is that the documentation is somewhat poor. I would love to get a little bit more information about how it works. Please contact me if you have some spare time and care to explain.
Shinigami · 11th May 2018 at 10:10 am
Hi Simon, sorry, I’m not an expert in bootstrap-datepicker and am currently on holiday so don’t have access to my development machine. If the reader doesn’t contain enough details you could check out the projects GitHub page https://github.com/uxsolutions/bootstrap-datepicker which should be able to provide you with more details and where you can raise an issue if you need help with anything specific. Good luck with the project.