I am trying to set a min and max date to my date inputs, the min setting is working but for some reason the max date is not. What is the problem here? I have also tried to use getDate() 90 instead of getMonth() 3.
my inputs:
let today = new Date().toISOString().split('T')[0];
let date3m = new Date(new Date().setDate(new Date().getMonth() 3));
document.getElementsByName("start")[0].setAttribute('min', today);
document.getElementsByName("start")[0].setAttribute('max', date3m)
<div class="calendar">
<div>
<label for="start">Start Dato:</label>
<input type="date" id="start" name="start" required>
</div>
<div>
<label for="end">Slutt Dato:</label>
<input type="date" id="end" name="end" required>
</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
min
and max
need to be in the format YYYY-MM-DD
. You're setting max
to something like Sat Nov 13 2021 18:14:51 GMT-0500 (Eastern Standard Time)
, which doesn't work.
Use toISOString()
just like you do for today
.
And setDate()
should be setMonth()
.
let today = new Date().toISOString().split('T')[0];
let date3m = new Date();
date3m.setMonth(date3m.getMonth() 3);
date3m = date3m.toISOString().split('T')[0];
document.getElementsByName("start")[0].setAttribute('min', today);
document.getElementsByName("start")[0].setAttribute('max', date3m)
<div class="calendar">
<div>
<label for="start">Start Dato:</label>
<input type="date" id="start" name="start" required>
</div>
<div>
<label for="end">Slutt Dato:</label>
<input type="date" id="end" name="end" required>
</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You forgot to remove the time from date3m
before setting the input's max
attribute to it.
let today = new Date().toISOString().split('T')[0];
let date3m = new Date(new Date().setDate(new Date().getMonth() 3)).toISOString().split('T')[0];
document.getElementsByName("start")[0].setAttribute('min', today);
document.getElementsByName("start")[0].setAttribute('max', date3m)
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>
<div class="calendar">
<div>
<label for="start">Start Dato:</label>
<input type="date" id="start" name="start" required>
</div>
<div>
<label for="end">Slutt Dato:</label>
<input type="date" id="end" name="end" required>
</div>
</div>
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>