簡體   English   中英

如何在一周而不是一天中使用 jQuery UI 日歷/日期選擇器?

[英]How to use jQuery UI Calendar/Date PIcker for week rather than day?

在過去的幾個月里,我一直在使用 jQuery UI 日歷/日期選擇器並取得了巨大的成功。 我收到了一項新要求,允許選擇一周(周日至周六)而不是一天。

有沒有人以前完成過這個?

  • 按周而不是按天突出顯示
  • 在文本框/標簽中顯示開始日期和結束日期而不是單個日期

使用jQuery UI DataPicker的內聯周選擇器(需要jQuery UI 1.8+):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
    var startDate;
    var endDate;

    var selectCurrentWeek = function() {
        window.setTimeout(function () {
            $('.week-picker').find('.ui-datepicker-current-day a').addClass('ui-state-active')
        }, 1);
    }

    $('.week-picker').datepicker( {
        showOtherMonths: true,
        selectOtherMonths: true,
        onSelect: function(dateText, inst) { 
            var date = $(this).datepicker('getDate');
            startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
            endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6);
            var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat;
            $('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings ));
            $('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings ));

            selectCurrentWeek();
        },
        beforeShowDay: function(date) {
            var cssClass = '';
            if(date >= startDate && date <= endDate)
                cssClass = 'ui-datepicker-current-day';
            return [true, cssClass];
        },
        onChangeMonthYear: function(year, month, inst) {
            selectCurrentWeek();
        }
    });

    $('.week-picker .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
    $('.week-picker .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
</script>
</head>
<body>
    <div class="week-picker"></div>
    <br /><br />
    <label>Week :</label> <span id="startDate"></span> - <span id="endDate"></span>
</body>
</html>

在JsFiddle http://jsfiddle.net/manishma/AVZJh/light/上運行它

我根據接受的答案創建了一個jQuery插件。 通過https://github.com/Prezent/jquery-weekpicker或通過Bower獲取。 用法示例:

$('#selector').weekpicker({
    startField: '#date-start',
    endField: '#date-end'
});

這是另一種方式。 - 用showWeek顯示一周。 - 使用live()定義beforeShow以附加事件處理程序,以便突出顯示周行(包括周數)。 - 使用die()onclose分離事件處理程序。 當您在代碼中的其他位置使用普通的日期選擇器時,這尤其方便。

$( ".week-picker" ).datepicker({
    dateFormat: "yy-mm-dd",
    showOtherMonths: true,
    selectOtherMonths: true,
    changeMonth: true,
    changeYear: true,
    showWeek: true,
    beforeShow: function(dateText, inst) { 

        // for week highighting
        $(".ui-datepicker-calendar tr").live("mousemove", function() { 
            $(this).find("td a").addClass("ui-state-hover"); 
            $(this).find(".ui-datepicker-week-col").addClass("ui-state-hover");
        });
        $(".ui-datepicker-calendar tr").live("mouseleave", function() { 
            $(this).find("td a").removeClass("ui-state-hover");
            $(this).find(".ui-datepicker-week-col").removeClass("ui-state-hover");      
        });
    },
    onClose: function(dateText, inst) { 
        var wk = $.datepicker.iso8601Week(new Date(dateText));
        if (parseInt(wk) < 10) {
            wk = "0" + wk;
        }           
        var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();

        if (isNaN(wk)) {
            $(this).val("");
        } else {
            $(this).val(year + ";" + wk);
        }

        // disable live listeners so they dont impact other instances
        $(".ui-datepicker-calendar tr").die("mousemove");
        $(".ui-datepicker-calendar tr").die("mouseleave");

    }
});

您需要以下依賴項:

  1. 的jquery.js
  2. jQuery的ui.min.js
  3. jQuery的ui.css

  var startDate; var endDate; $('.date-picker').datepicker( { changeMonth: true, changeYear: true, showButtonPanel: true, onSelect: function(dateText, inst) { var date = $(this).datepicker('getDate'); startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay()); endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 6); var dateFormat = inst.settings.dateFormat || $.datepicker._defaults.dateFormat; $('#startDate').text($.datepicker.formatDate( dateFormat, startDate, inst.settings )); $('#endDate').text($.datepicker.formatDate( dateFormat, endDate, inst.settings )); $(this).val($.datepicker.formatDate( dateFormat, startDate, inst.settings ) + " - " + $.datepicker.formatDate( dateFormat, endDate, inst.settings )); } }); 
 .ui-datepicker-calendar tr:hover { background-color:#808080; } 
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script> <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css"> </head> <body> <label for="startDate">Date :</label> <input name="startDate" class="date-picker" /> <label>Week :</label> <span id="startDate"></span> - <span id="endDate"></span> </body> </html> 

我在第8123行修改了jqueryui-1.10.2.js:

(我不記得我在哪里見過這個)

case 'W':  
output += this.iso8601Week(new Date(date.getFullYear(), date.getMonth(), date.getDate()));
break;

然后你可以用日期格式選擇W周==> dateFormat:'yy-W'

$("#your_datepicker").datepicker ({ firstDay: 1, showWeek: true, showOtherMonths: true, dateFormat: 'yy-W'});

如果您有以前版本的jqueryui,請在文件中搜索“@”(也搜索引號)並添加這3行。

我使用了上面的一些示例,但采用了不同的方法,因為我需要支持選擇一周但是一周可以在一周的任何一天開始,並且需要根據變量進行更改。 我設置了一個課程,用每周課程對每個td進行分組,這樣我就可以輕松地突出顯示與tr重疊的一周。 在此示例中,datepickerStartWeekDay可以是0到6,表示從星期日到星期六開始的一周。

這是我的代碼:

var $elem = $("input.my-date-picker");
var weekCounter = 1;
var datepickerStartWeekDay = 1;

options = {
    changeMonth: true,
    changeYear: true,
    showOtherMonths: true,
    selectOtherMonths: true,
    onClose: function (dateText, inst) {
        weekCounter = 1;
    },
    onSelect: function(dateText, inst) {
        if (datepickerStartWeekDay != null) {
            var elem = $(this);
            var date = elem.datepicker('getDate');
            var curDayNum = date.getDay();
            var offset;

            if (curDayNum > datepickerStartWeekDay) {
                offset = -(curDayNum - datepickerStartWeekDay);
            }
            else {
                offset = -(7 - (datepickerStartWeekDay - curDayNum));
            }
            var wkStartDate = new Date(date.addDays(offset));
            elem.val(wkStartDate);
        }
    },
    beforeShowDay: function(date) {
        var retClass;

        // datepickerStartWeekDay:  0 = Sunday.. 6 = Saturday
        // Set up weeks based on the start day with classes.
        // week1, week2, week3, etc based on the start day of the week
        if (datepickerStartWeekDay != null) {
            if (date.getDay() == datepickerStartWeekDay) {
                weekCounter += 1;
            }
            retClass = [true, 'week' + weekCounter];
        }
        else {
            retClass = [true, ''];
        }
        return retClass;
    },
    onChangeMonthYear: function(year, month, inst) {
        weekCounter = 1;
    }
};
$elem.datepicker(options);

// Event to list for mouseover for week selection
$(".ui-datepicker-calendar td").live('mouseover', function (ev) {
    var targetElem = $(ev.currentTarget);
    targetElem.closest("tbody").find(".ui-week-hover").removeClass("ui-week-hover");
    for (var i = 0; i < 8; i++) {
        if (targetElem.hasClass("week" + i)) {
            targetElem.closest("tbody").find(".week" + i).addClass("ui-week-hover");
            continue;
        }
    }
});`

// CSS

.ui-week-hover a {
    background-color: #eef6f9 !important;
}

如果有人仍然感興趣我就做了這個: Week Picker Converter

是一個小型字段轉換器,可將文本或隱藏轉換為周選擇器。 如果有人使用它來打印表(來自數據庫),那么在SQL查詢選擇中使用以下模式也可以使用它:

select
'<span class="displayWeek">'
|| week_field
|| '</span><input type="hidden" value="week_field" id="id_field" />'
|| '<i class="fa fa-calendar showCalendar" aria-hidden="true"
    style="cursor:pointer;margin-left: 10px;"
    onclick="javascript:showWeekCalendar(this, additionalFunction);"></i>'
as "WeekPicker"
from dual
$(function () {
  var date = $('#FromDate').datepicker('getDate');
  date.setMonth(date.getMonth() + 1);
  var year = date.getFullYear(); //get year
  var month = date.getMonth();
  var date1 = date.getDate();
  $("#ToDate").datepicker("setDate", date);

  $("#ToDate").datepicker({
    //In Datepicker set the Calendar display start with Monday

    firstDay: $('#FromDate').datepicker('getDate'),
    //stepMonths: 0 ,
    //month: date.getMonth(), 
    showOtherMonths: true,
    selectOtherMonths: true,
    startDate: new Date(month, date1, year), //set it here
    endDate: new Date(month, '31', year + 1),
    beforeShowDay: function (date) {
      //var monday = new Date("June 1, 2013 00:00:00"); Used it for testing

      //Get today's date
      var monday = $('#FromDate').datepicker('getDate');

      //Set the time of today's date to 00:00:00
      monday.setHours(0, 0, 0, 0);

      //alert(monday.getDay() + ' : ' + monday.getDate() + ' : ' + (monday.getDay() || 7) + ' : ' + monday); Used it for testing

      /*
      Below Line sets the Date to Monday (Start of that Week)
      (monday.getDay() || 7) returns the value of getDay()
      ie., [ 1 - Mon, 2 - Tue, 3 - Wed, 4 - Thu, 5 - Fri, 6 - Sat ]
      except for Sunday where it returns 7.
      The return value is used to calculate the Date of that Week's Monday
      */

      monday.setDate(monday.getDate() + 1 - (monday.getDay() || 7));

      //Set the Date to Monday
      var sunday = new Date(monday);

      //Now add 6 to Monday to get the Date of Sunday (End of that Week)
      sunday.setDate(monday.getDate() + 6);
      //Now return the enabled and disabled dates to datepicker
      return [(date >= monday && date <= sunday), ''];
    },

  });

  //Set the date format to dd/mm/yy ie., 30/10/1989
  $("#ToDate").datepicker("option", "dateFormat", "mm/dd/yy");
});

 $(function(){ $('#week-button').click(function() { var value = $("#weeklyDatePicker").val(); const search = new URLSearchParams(location.search); search.set('week_start', value.split(" ")[0]); search.set('week_end', value.split(" ")[2]); location.search = search.toString(); }); }); $(document).ready(function(){ moment.updateLocale('en', { week: { dow: 1 } // Monday is the first day of the week }); //Initialize the datePicker(format mm-dd-yyyy) $("#weeklyDatePicker").datepicker({ format: 'MM-DD-YYYY', firstDay: 1 }); //Get the value of Start and End of Week $('#weeklyDatePicker').on('change', function (e) { var value = $("#weeklyDatePicker").val(); var firstDate = moment(value, "MM-DD-YYYY").day(1).format("YYYY-MM-DD"); var lastDate = moment(value, "MM-DD-YYYY").day(7).format("YYYY-MM-DD"); $("#weeklyDatePicker").val(firstDate + " - " + lastDate); }); });
 .ui-datepicker-calendar tbody tr:hover { background-color: #a768f3; color: #444444; } .ui-datepicker-calendar tbody tr:hover td , .ui-datepicker-calendar tbody tr:hover a { background: transparent !important; color:#fff !important; font-weight:bold; }
 <script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <input autocomplete="off" class="week-picker form-control" type='text' name="week" id="weeklyDatePicker" placeholder="Select Week" />

暫無
暫無

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

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