简体   繁体   English

如何动态禁用jQuery datepicker中的特定日期?

[英]how to dynamically disable specific date in jquery datepicker?

I am trying to dynamically disable date (jquery datepicker) which is already in database. 我试图动态禁用数据库中已经存在的日期(jquery datepicker)。 I have done static method in that I am able to achieve goal but not getting success in dynamic approach 我已经完成了静态方法,因为我能够达到目标,但无法在动态方法中获得成功

<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];
    }
});

And here is my controller code: 这是我的控制器代码:

    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;
        }

Disable doesn't work well with date picker. 禁用不适用于日期选择器。 Try my plnkr. 试试我的plnkr。

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

It gets the datepicker on click and parses through the dates and data set given and if a match is found it removes the click event on it. 它获取单击时的日期选择器,并解析给定的日期和数据集,如果找到匹配项,它将删除其上的click事件。 and repeats on each render please see my plnkr link for html. 并在每个渲染器上重复,请参见我的plnkr html链接。 Hope it helps 希望能帮助到你

<!--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>

Your original idea is in the right direction, but I think there's probably something weird going on with all the string conversion. 您最初的想法是朝正确的方向发展,但是我认为所有字符串转换可能都有些奇怪。 I'd just pass through dates and compare with dates rather than all the stringy stuff: I've written this quick test... 我只是经过日期并与日期进行比较,而不是与所有繁琐的东西进行比较:我已经编写了此快速测试...

controller: 控制器:

//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();

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>

This appears to work for me. 这似乎为我工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM