set min date with jqruery html5 native picker

Viewed 31

i have problem to set min date attribute, on single page i have 25+ input type date for different products. I can see value of attribute min is set to today date, but i can pick date before today(fields are not disabled)

let today = new Date();
let dd = today.getDate();
let mm = today.getMonth() + 1;
let yyyy = today.getFullYear();
let dateList = $('.pickupdate');
let list = dateList.length;
let index = 0;
today = yyyy + '-' + mm + '-' + dd;
for (index = 0; index < list; ++index) {
  let dateList2 = dateList[index];
  $(dateList2).attr('min', today);
  dateList[index];
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input 
  id="pickupdate" 
  type="date" 
  class="date-basic font-w-500 clr-white pickup m-0 datechk pickupdate" 
  name="pickupdate" 
  placeholder="dd/mm/yyyy"
  min="1899-01-01" max="" 
  value="{{$request->pickupdate}}" 
  required 
/>

1 Answers

The issue is due to the dateformat you're generating - YYYY-M-D. For it to work correctly it has to be YYYY-MM-DD. As such you need to include leading zeros in the day and month values, which can be easily done with a helper function.

Also note that I amended your logic to set the attr() on each date field. If you're using jQuery then use the each() method to loop over elements, not for. Also, the loop itself is redundant as jQuery will do it for you. Finally, if you have repeating HTML do not put id attributes on those elements as id have to be unique within the DOM.

With all that said, try this:

let leadingZero = value => value.toString().padStart(2, '0').slice(-2);

let today = new Date();
let dd = leadingZero(today.getDate());
let mm = leadingZero(today.getMonth() + 1);
let yyyy = today.getFullYear();

$('.pickupdate').attr('min', `${yyyy}-${mm}-${dd}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" class="pickupdate" name="pickupdate" placeholder="dd/mm/yyyy" min="1899-01-01" max="" value="" required />

Related