如何在jquery datepicker中动态禁用特定日期?

时间:2017-10-04 16:16:56

标签: javascript jquery asp.net-mvc jquery-ui datepicker

我正在尝试动态禁用已存在于数据库中的日期(jquery datepicker)。我已经完成了静态方法,因为我能够实现目标但却没有在动态方法中获得成功

<script language="javascript">
$(document).ready(function () {
    var getfromdb = @Html.Raw(@ViewBag.bookdate);
    var result = '\'' + getfromdb.toString().split(',').join('\',\'') + '\'';
    var disableddates = [result];

    var newdisableddates = ['17/10/2017','18/10/2017','19/10/2017','22/10/2017','23/10/2017','24/10/2017','25/10/2017'];  // Static Approach 

    $("#txtFromdate").datepicker({
        minDate: 0,
        beforeShowDay: DisableSpecificDates,
        dateFormat: 'dd/mm/yy'
    });
    $("#txtTodate").datepicker({
        minDate: 0,
        beforeShowDay: DisableSpecificDates,
        dateFormat: 'dd/mm/yy'
    });

    function DisableSpecificDates(date) {
        var string = jQuery.datepicker.formatDate('dd/mm/yy', date);
        return [disableddates.indexOf(string) == -1];
    }
});

这是我的控制器代码:

    List<string> getbookdate = new List<string>();
    getbookdate = BookDate(id);
    ViewBag.bookdate = JsonConvert.SerializeObject(getbookdate.ToList());


     public List<string> BookDate(int? id)
        {
            DateTime dt = System.DateTime.Now.Date;
            var getbookdate = (from x in entity.BookingMasters
                               join
                               y in entity.BookingDetails on x.BookingId equals y.BookingId
                               where x.ProductId == id && y.FromDate > dt && y.ToDate > dt
                               select new BookingModel { ProductId = x.ProductId.Value, FromDate = y.FromDate.Value, ToDate = y.ToDate.Value }).ToList();

            List<string> allDates = new List<string>();

            foreach (var r in getbookdate)
            {
                for (DateTime date = r.FromDate; date <= r.ToDate; date = date.AddDays(1))
                {
                    allDates.Add(Convert.ToString(date.ToShortDateString()));
                }
            }
            return allDates;
        }

2 个答案:

答案 0 :(得分:0)

禁用对日期选择器不起作用。试试我的plnkr。

https://embed.plnkr.co/h4RaeIKJVfj9IjyHREqZ/

它在点击时获取日期选择器并解析给定的日期和数据集,如果找到匹配项,则会删除其上的点击事件。并在每个渲染重复,请参阅我的plnkr链接的HTML。希望它有所帮助

<!--Disable doesn't work well with date picker. Try this. Hope it helps-->
<!--Working example https://embed.plnkr.co/h4RaeIKJVfj9IjyHREqZ/ -->
<!--Code-->
<!--HTML PART-->
<!DOCTYPE html>
<html>

<head>
  <script data-require="jquery@3.1.1" data-semver="3.1.1" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script data-require="tether@*" data-semver="1.4.0" src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js"></script>
  <link data-require="bootstrap@4.0.5" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />
  <link data-require="jqueryui@*" data-semver="1.12.1" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" />
  <script data-require="jqueryui@*" data-semver="1.12.1" src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
</head>

<body class="container">
  <h1>Hello User</h1>
  <div class="box">
    <div class="box-content">
      <div class="row">
        <div class="col-md-4">
          <label>Date:</label>
          <input type="text" id="date-picker-control" />
        </div>
      </div>
    </div>
  </div>
  <script>
    var element = $('#date-picker-control');
    element.datepicker();

    element.off('click').on('click', function() {

      // Setup DatePicker
      console.log('Update Date Picker');

      // If user changes month or year, update date picker 
      // based on the date list you have 
      $("#ui-datepicker-div")
        .find("div.ui-datepicker-header")
        .find('a.ui-datepicker-next, a.ui-datepicker-prev')
        .on('click', function() {
          element.click();
        });

      // Get all available dates in current displayed dates
      var availableDates = $("#ui-datepicker-div")
        .find("table.ui-datepicker-calendar")
        .find('td[data-handler="selectDay"]');

      availableDates.filter(function(i) {
        var targetDateElement = $(this);

        //Get date parts
        var year = +targetDateElement.data("year");
        var month = targetDateElement.data("month") + 1; //JS fix
        var day = +targetDateElement.find('a.ui-state-default').text();
        var builtDate = month + '/' + day + '/' + year;

        // you can substitute your json data
        var targetDates = [
          "10/2/2017", "10/6/2017", "10/8/2017"
        ];

        $.each(targetDates, function(i, targetDate) {
          // If builtDate match targetdate then turn click event oFF on that date
          if (targetDate == builtDate) {
            targetDateElement.css({ 
              'border': '1px solid gray',
              'background': 'darkgray',    
              'font-weight': 'bold',
              'color': 'gray'
            }).off('click');
          }
        });

      });
    });
  </script>
</body>

</html>

答案 1 :(得分:0)

你最初的想法是正确的方向,但我认为所有的字符串转换可能都有些奇怪。我只是通过日期并与日期进行比较而不是所有粗俗的东西: 我写了这个快速测试...

控制器:

//Replace with however you get dates
 ViewBag.DatesList = new List<DateTime>() 
    { 
        new DateTime(2018, 01, 01), 
        new DateTime(2018, 01, 02), 
        new DateTime(2018, 01, 03) 
    };
    return View();

查看:

<script language="javascript">
$(document).ready(function () {

var disableddates = [];
@foreach (DateTime date in ViewBag.DatesList)
{
    //note JS month is zero-based for no good reason at all... 
    @:disableddates.push(new Date(@date.Year, @date.Month-1, @date.Day))
}

$("#txtFromdate").datepicker({
    minDate: 0,
    beforeShowDay: DisableSpecificDates,
    dateFormat: 'dd/mm/yy'
});
$("#txtTodate").datepicker({
    minDate: 0,
    beforeShowDay: DisableSpecificDates,
    dateFormat: 'dd/mm/yy'
});

function DisableSpecificDates(date) {
    //filter array to find any elements which have the date in.
    var filtereddates = disableddates.filter(function (d) {
        return d.getTime() === date.getTime();
    });

    //return array with TRUE as the first (only) element if there are NO 
    //matching dates - so a matching date in the array will tell calling 
    //code to disable that day.
    return [filtereddates.length == 0];
}
});
</script>

这似乎对我有用。