Created
May 18, 2016 18:30
-
-
Save raiderrobert/b83f096c0f3c37cc8c0014d6375d32c7 to your computer and use it in GitHub Desktop.
Date enforcer dependent on jquery and moment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var dateEnforcer = function (startDate, endDate) { | |
$(startDate).on('focus', function () { | |
this.previousDate = moment(this.value).format('MM-DD-YYYY'); | |
}).change(function(){ | |
var newDate = moment(this.value).format('MM-DD-YYYY'); | |
var endDateMoment = moment($(endDate).val()).format('MM-DD-YYYY'); | |
if (this.previousDate != 'Invalid date'){ | |
if (moment(newDate).isAfter(endDateMoment)){ | |
$(endDate).val(newDate); | |
} | |
} else { | |
$(endDate).val(newDate); | |
} | |
}); | |
$(endDate).on('focus', function () { | |
this.previousDate = moment(this.value).format('MM-DD-YYYY'); | |
}).change(function(){ | |
var newDate = moment(this.value).format('MM-DD-YYYY'); | |
var startDateMoment = moment($(startDate).val()).format('MM-DD-YYYY'); | |
if (this.previousDate != 'Invalid date'){ | |
if (moment(newDate).isBefore(startDateMoment)){ | |
$(startDate).val(newDate); | |
} | |
} else { | |
$(startDate).val(newDate); | |
} | |
}); | |
}; | |
dateEnforcer('#id_from_date', '#id_to_date'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This compares dates so that if you're using a calendar widget and are having a date that has a range that it should apply to, this will ensure you can't flip the range accidentally.