簡體   English   中英

如何動態禁用jQuery datepicker中的特定日期?

[英]how to dynamically disable specific date in jquery 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;
        }

禁用不適用於日期選擇器。 試試我的plnkr。

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

它獲取單擊時的日期選擇器,並解析給定的日期和數據集,如果找到匹配項,它將刪除其上的click事件。 並在每個渲染器上重復,請參見我的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>

您最初的想法是朝正確的方向發展,但是我認為所有字符串轉換可能都有些奇怪。 我只是經過日期並與日期進行比較,而不是與所有繁瑣的東西進行比較:我已經編寫了此快速測試...

控制器:

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

這似乎為我工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM