Contador6 Contador6 - 1 month ago 20
HTML Question

Change attribute min of input type=date in javascript

I have two input fields of type date.

<input id="startdate" type="date" min='@DateTime.Now.AddDays(1).ToShortDateString()' onchange="handler(event)" />
<input id="enddate" type="date" min="@DateTime.Now.AddDays(2).ToShortDateString()" onchange="handler(event)" />


I want in enddate min date be alaways two days ahead towards selected date in start date. So far I use script adding days and selecting attribute min.

<script type="text/javascript">
function handler(e) {
var someDate = new Date($("#startdate").val());
document.getElementById("enddate").setAttribute('min', addDays($("#startdate").val(),2));
}
</script>

<script type="text/javascript">
function addDays(date, days) {
var result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
</script>


This proposition is not working. Any ideas?

Answer Source

using moment.js

<input id="startdate" type="date" min='' />
<input id="enddate" type="date" min="" />

<!-- import moment.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script>
(function(){
  $('#startdate').attr('min', moment().format('YYYY-MM-DD'))

  $('#startdate').on('change', function(e){
    var startDate = $(this).val();
    var endDate = moment(startDate).add(2, 'days').format('YYYY-MM-DD');
    $('#enddate').attr('min', endDate);
  })
})()
</script>