Home > database >  how to disable array of date from date input in html
how to disable array of date from date input in html

Time:08-15

I have an HTML <input /> with type=date that I will like to disable the array of dates and I tried the below code but couldn't get the date disabled:

<script>

    const chooseDay = document.querySelector('input[name="end_time"]');

    const handleDateChange = ({ target: dateField }) => {
        const
        { dataset: { unallowed = '[]' }, value } = dateField,
        unallowedDates = JSON.parse(unallowed),
        valid = !unallowedDates.includes(value);
        if (!valid) { dateField.value = null; }
        dateField.classList.toggle('invalid', !valid);
    };

    chooseDay.addEventListener('change', handleDateChange);

</script>

<input type="date" name="end_time"  
    data-unallowed='["2022-08-25","2022-08-20","2022-08-22"]' />

Can anyone help with any idea to disable the dates in the array above? Thanks in advance.

CodePudding user response:

As per the comment above, the code appeared to work OK as a snippet but could be simplified somewhat perhaps?

const changehandler=function(e){
  if( this.dataset.unallowed.includes( this.value ) ){
    this.classList.add('invalid');
    this.value=null;
    return false;
  }
  this.classList.add('valid');
};

document.querySelector('input[type="date"][name="end_time"]').addEventListener('change',changehandler);
.invalid{background:rgba(255,0,0,0.25)}
.valid{background:rgba(0,255,0,0.25)}
<input type="date" name="end_time"  
    data-unallowed='["2022-08-25","2022-08-20","2022-08-22"]' />

CodePudding user response:

<input type="date" name="party" min="2022-08-22" max="2022-08-25">

The result is that only the specified date can be sectioned and the rest cannot be selected in the selection widget.

  • Related