In my MVC 2 application, I have many views with many, many input fields. Quite a lot of them contain DateTime variables.
I am using the datepicker jQuery plugin to help the user select the date. This also allows me to do the following in my MasterPage:
$(document).delegate(".hasDatepicker", "keyup", function () {
this.value = this.value.replace(/[^0-9\.\/]/g, '');
});
This is to eliminate users from using incorrect characters if they prefer to type. Since Datepicker adds its own class to datepicker-elements, I was able ot use that class to automatically clean up input.
No issues here, This is the part that works like it should.
The problem however, is that when I open an Edit view, the Textbox is populated with “21/05/2012 0:00:00”. Once you start using the Datepicker plugin, it gets changed to only the date, as it should.
To remove the Time-part from the textbox, I was thinking about doing:
$(".hasDatepicker").each( function() {
$(this).val($this.val().replace(" 0:00:00",""));
});
Which seems to me to be the easiest solution.
But then I would have to add it to every page, and I was wondering if there is a way to make a .delegate() version of this. Something along the lines of
$(document).delegate(".hasDatepicker", SOME_EVENT, function () {
$(this).val($this.val().replace(" 0:00:00",""));
});
The problem is, what should SOME_EVENT be? I want this to be triggered when the “hasDatepicker” class has been added, so that I know which textboxes to clear (there are other textboxes for remarks etc that also contain that string, but these should not be replaced.
Is there such an event that triggers on class change?
Or any other way to solve this without me having to copy paste it on every page? 🙂
why do you use this complex way to edit the date format when jQuery datepicker has a builtin functionality doing just that using the dateFormat option:
fro jquery ui docs: