shaneklive shaneklive - 3 months ago 9
jQuery Question

jQuery datepicker disable sundays & specific array of dates

I've gotten pretty far with this but stuck on the last part. I basically just need to disable all sundays and then be able to add dates to an array to also be disabled, I know the code to disable each individually but when I try to put them together I either get sundays with the array of dates selectable or the other way around. The two parts I need to join to have the array and sundays disable are in the beforeshowdays functions, I know I can't have two I just put both in so you can see what I'm trying. Thanks for any help

<script>
var array = ["2016-08-29","2013-03-15","2013-03-16"]
</script>

<script>

$( function() {

var today = new Date();

$( "#datepicker" ).datepicker({
dateFormat: 'dd MM yy',
beforeShowDay: function(date) {
var day = date.getDay();
return [(day != 0), ''];
},
beforeShowDay: function(date) {
var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
return [ array.indexOf(string) == -1 ]
},
//beforeShowDay: $.datepicker.noWeekends,
firstDay: 1,
minDate: today.getHours() >= 14 ? 2 : 1,
maxDate: '+1m',
onSelect: function(dateText, inst) {
$('#checkout_attribute_1').val(dateText);
}
});
} );
</script>

Answer

You can try something like this :

var array = ["2016-08-29", "2013-03-15", "2013-03-16"]

$(function() {
  var today = new Date();
  $("#datepicker").datepicker({
    dateFormat: 'dd MM yy',
    beforeShowDay: function(date) {
      var string = jQuery.datepicker.formatDate('yy-mm-dd', date);
      if (contains(array,string)) {
        debugger;
        return [false, '']
      } else {
        var day = date.getDay();
        return [(day != 0), ''];
      }
    },
    //beforeShowDay: $.datepicker.noWeekends,
    firstDay: 1,
    minDate: today.getHours() >= 14 ? 2 : 1,
    maxDate: '+1m',
    onSelect: function(dateText, inst) {
      $('#checkout_attribute_1').val(dateText);
    }
  });
});

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

https://jsfiddle.net/9hrhyd4q/