1

I have input type="date" in my html page and I want to disable particular date through JavaScript. How can I do that?

I have tried to disable using getElementById but its disabling complete date input.

marzzy
  • 706
  • 10
  • 21
chandu
  • 11
  • 1
  • 1
  • 5

2 Answers2

0

You can add a min or max attribute to the input type=date. The date must be in ISO format (yyyy-mm-dd). This is supported in many mobile browsers and current versions of Chrome, although users can manually enter an invalid date without using the datepicker.

<input name="somedate" type="date" min="2017-11-25">

The min and max attributes must be a full date; there's no way to specify "today" or "+0". To do that, you'll need to use JavaScript or a server-side language:

    var today = new Date().toISOString().split('T')[0];
document.getElementsByName("somedate")[0].setAttribute('min', today);

What we can’t do yet, however, is eliminate classes of days from our input. We can’t, for example, prevent selection of weekends or disallow Mondays purely through markup. Instead, we’ll need to do a little more work, using the HTML5 validation API, and the native JavaScript Date object.

code that will display an error if the date selected is a Monday.

    var date = document.querySelector('[type=date]');

function noMondays(e){

    var day = new Date( e.target.value ).getUTCDay();

    // Days in JS range from 0-6 where 0 is Sunday and 6 is Saturday

    if( day == 1 ){

        e.target.setCustomValidity('OH NOES! We hate Mondays! Please pick any day but Monday.');

    } else {

        e.target.setCustomValidity('');

    }

}

date.addEventListener('input',noMondays);
Blesson Christy
  • 380
  • 3
  • 13
0

You could set a maximum/minimum on your date attribute like shown over here: https://www.w3schools.com/tags/att_input_min.asp

This however does not let you disable specific dates. If you really want this I would check if the selected date is allowed on posting the form.

You could get the selected date value on a submit like this in JQuery:

 $('#submit').on('click', function(){
      var date = new Date($('#date-input').val());

      day = date.getDate();
      month = date.getMonth() + 1;
      year = date.getFullYear();

      //Check here if date, month and year combination is allowed
 });

In this example we have a date element with id 'date-input' and a button with id 'submit'.

Note that you should also check if the date is allowed on the server side.

JKL
  • 978
  • 7
  • 21