I'm not sure what even you want this to fire on, so I'm assuming you may want to fill the next box after first one loses focus. You may adjust that to your needs by changing the event to keyup
, change
or whatever.
$('#ActivationReqDTTextBox').blur(function () {
var myDate = new Date(Date.parse($(this).val()));
myDate.setYear(myDate.getYear() + 1);
$('#DeactivationReqDTTextBox').val(myDate);
});
Couple of things to be aware of:
- you have to make sure that your date format is compatible with the
Date.parse
and if it's not then you need to reformat it before use
- you may want to format the result date as well
Date.parse
expects MM/DD/YYYY and in your case it's DD/MM/YYYY so you need to swap month with the day. This will do the trick:
function reformat(a) {
return a.substring(3,5) + '/' + a.substring(0,2) + a.substring(5, 10);
}
Given that modified code from above should look like that.
$('#ActivationReqDTTextBox').blur(function () {
var myDate = new Date(Date.parse(reformat($(this).val())));
$('#DeactivationReqDTTextBox').val(myDate.getDate() + '/' +
(myDate.getMonth() + 1) + '/' + (myDate.getYear() + 1));
});
EDIT:
To make sure the script doesn't fire up when incorrect date is entered in the first field you could do this:
$('#ActivationReqDTTextBox').blur(function () {
var value = $(this).val();
var regex = /^\d{2}\/\d{2}\/\d{4}$/;
if (regex.test(value)) {
var myDate = new Date(Date.parse(reformat(value)));
$('#DeactivationReqDTTextBox').val(myDate.getDate() + '/' +
(myDate.getMonth() + 1) + '/' + (myDate.getYear() + 1));
} else {
alert('invalid date');
// this will prevent from leaving the input until the date is correct
$(this).focus();
}
});
EDIT #2:
One more update to the code. This will prevent leading zeros for months and days.
$('#ActivationReqDTTextBox').blur(function () {
var value = $(this).val();
var regex = /^\d{2}\/\d{2}\/\d{4}$/;
if (regex.test(value)) {
var myDate = new Date(Date.parse(reformat(value)));
var year = myDate.getYear() + 1;
var month = myDate.getYear() + 1;
if (month < 10) {
month = '0' + month;
}
var day = myDate.getDate();
if (day < 10) {
day = '0' + day;
}
$('#DeactivationReqDTTextBox').val(day + '/' + month + '/' + year);
} else {
alert('invalid date');
// this will prevent from leaving the input until the date is correct
$(this).focus();
}
});