Dealing with Multiple jQuery datepickers on a single page.

Wow, it’s been an awful long time since I posted my first blog post and to my surprise its had lot’s of views and due to a change in job I just haven’t had the time to come back here and keep posting up code snippets.  Recently I’ve been tasked with web design problems that other developers have left behind.

Firstly was the issue that we had a razor page which was having datepickers (jquery) being generated on the fly based on an x input.

Therefore the previous developer had left each datepicker assigned the same id, so when you update one box, it updates them all.

After some digging I came up with the following solution:

This is an example of the code that’s generating the datepickers.

@for(int p =0; p <Model.InputParameters.Count; p++){
if(Model.InputParameters[p].DatePicker))
{
var id ="datepicker"+ p;
@Html.TextBoxFor(modelitem =>Model.InputParameters[p].Value,DateTime.Now.ToString("dd/MM/yyyy"),new{@id= id,@class="datepicker"})
}
//the clever bit of javascript that allows us to update each datepicker separatel
$(document).ready(function (){     
$('.datepicker').each(function (){
$(this).datepicker({ dateFormat:"dd/mm/yy"});});})