Hello,
this time i do not have anything my own and could not find also!
The idea is if user from first date input pick
today date lets say 2017-06-29 than automatically would not allow dates that are over 7 calendar days
so now he could select max to 2017-07-06 (including)
then you have to validate the second input based on the first input (hooking into the second field’s change event) and reject the second input if the validation fails.
Ideally you’d set that max-value on the backend, so that there is no JS required at all… also, formatting dates is much easier with PHP. But you could of course set it with JS as well:
var dateInput = document.querySelector('[type=date]')
var date = new Date()
date.setDate(date.getDate() + 7)
var maxDate = date.getFullYear() +
'-' + (date.getMonth() + 1).toString().padStart(2, '0') +
'-' + date.getDate().toString().padStart(2, '0')
dateInput.max = maxDate
Oh wow i would never write such a javascript code
Looks like it works!
I need to add +6 days as i need it to be 7 calendar days?correct?
Also why i wanted to set other input?Well then each time user edits first input he will never be able to enter date 7+ days.
In your code if i edit first input i can get more than 7 days
True, if you change the 1st input to some earlier date, the 2nd won’t update automatically (but it would still get marked as invalid when you try to submit the form). However you might also just set the 2nd value to the new maxDate when the 1st changes and the 2nd isn’t valid any more – you can compare date objects with < and > just like numbers:
firstDate.addEventListener('change', function () {
var date = new Date(this.value)
var current = new Date(secondDate.value)
date.setDate(date.getDate() + 7)
var maxDate = date.getFullYear() +
'-' + (date.getMonth() + 1).toString().padStart(2, '0') +
'-' + date.getDate().toString().padStart(2, '0')
secondDate.max = maxDate
if (current > date) {
secondDate.value = maxDate
}
})