27

標準の Jquery UI 日付ピッカーで 1 週間全体を強調表示できますか?

4

12 に答える 12

27

この投稿はかなり古いことは知っていますが、別のサイトでこのコードを見つけたところ、役立つかもしれないと思いました。

ソースコード-この投稿から:

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

>>

于 2011-09-14T06:25:34.540 に答える
4

これに対する解決策を書きました。これは、その週を強調しています。選択した日付は引き続き選択されますが、それは私の目的には問題ありません。#week は、datepicker が添付された入力ボックスです。

$('#week').datepicker({

  beforeShowDay: $.datepicker.noWeekends,
  duration : 0,
  onChangeMonthYear: function() {   setTimeout("applyWeeklyHighlight()", 100); },
  beforeShow: function() { setTimeout("applyWeeklyHighlight()", 100); }

}).keyup(function() { setTimeout("applyWeeklyHighlight()", 100); });

function applyWeeklyHighlight()
{

    $('.ui-datepicker-calendar tr').each(function() {

        if($(this).parent().get(0).tagName == 'TBODY')
        {
            $(this).mouseover(function() {
                    $(this).find('a').css({'background':'#ffffcc','border':'1px solid #dddddd'});
                    $(this).find('a').removeClass('ui-state-default');
                    $(this).css('background', '#ffffcc');
            });
            $(this).mouseout(function() {
                    $(this).css('background', '#ffffff');
                    $(this).find('a').css('background','');
                    $(this).find('a').addClass('ui-state-default');
            });
        }

    });
}
于 2011-10-11T15:05:18.207 に答える
2

AntFalco の答えは素晴らしいですが、私がやったことをする必要がある場合はうまくいきません。週を選択し、週の最初の日を入力ボックスに入力する方法が必要でした。クリックすると、日付ピッカーが生成されました。これを達成するために使用したコードは次のとおりです。

<!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.9.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
    var startDate;
    var endDate;

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

    $('.datepicker').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;
            $(this).attr("value",$.datepicker.formatDate( dateFormat, startDate, 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();
        }
    });

    $('#ui-datepicker-div .ui-datepicker-calendar tr').live('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
    $('#ui-datepicker-div .ui-datepicker-calendar tr').live('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });
});
</script>
</head>
<body>
    <input type="text" id="from_date" name="from_date" class="datepicker" />
    <input type="text" id="to_date" name="to_date" class="datepicker" />
</body>
</html>

これには、複数の入力値に対しても機能するという副作用もあります。このコードのチャンクは、何らかの「週」セレクターが必要な場合に最も役立ちます。コードはほとんどないため、テストに小さな変更を加えるのは非常に簡単です。また、minDate/maxDate 関数でも問題なく動作します。

于 2013-04-25T22:40:37.430 に答える
2

これは、datepicker を使用して 1 週間全体を選択する方法の例を含む記事です。

$(function()
{
    $('.date-pick').datePicker({selectWeek:true,closeOnSelect:false});
});    
于 2010-02-08T19:14:40.880 に答える
1

これは信じられないほど遅いですが、私は同じ解決策を探していて、これらのタイプの回答への参照しか見つけることができませんでした(つまり、別の日付ピッカーの場合)。私の場合、インラインで使用しているので、このコードはこのように機能します。週が強調表示された状態でポップアップ表示する場合は、変更する必要があります。これが機能するものです:

var selectedWeek;//remember which week the user selected here
$("#inlineDIVdatepicker").datepicker({
    firstDay:1,
    showOtherMonths:true,
    onSelect: function(dateText){
       selectedWeek = $.datepicker.iso8601Week(new Date(dateText));
    } ,

    //set the class 'week-highlight' for the whole week
    beforeShowDay: function(d){
        if (!selectedWeek) { return [true,''];}
        if (selectedWeek == $.datepicker.iso8601Week(d)){
              return [true,'week-highlight'];   
        }
        return [true,''];
    }
});

次に、CSSを定義します(私は実際にはこの部分を自分で行っていないので、これは醜いです):

#inlineDIVdatepicker .week-highlight a {
  background:none;
  background-color:yellow;  
}
于 2010-11-16T17:41:37.827 に答える
1

このディスカッションの提案に従って、週の選択機能を実現できる場合があります: http://code.google.com/p/jquery-datepicker/issues/detail?id=13

残念ながら、jQuery の datepicker では 1 週間全体を選択することはできないようです。カスタムコーディングする必要があります。

于 2010-02-08T19:11:22.187 に答える
1

編集:フリクションレスの答えは素晴らしいですが、問題は週全体を選択する方法でした(クリックされた後の6日間ではありません)。ここにパッチをコピーすることをお勧めします。

これは、私が自分のサイトで使用しているものの簡易版です。週の最初と最後の曜日を表示するために、週ピッカーは <span> タグに固定されていることに注意してください。これには、/images/schedule.png を参照するトリガー ボタンが必要です。

必要に応じて変更します。

<style type="text/css">
    .highlighted-week a.ui-state-default{
        background: #FFFFFF;
        border: 1px solid #AAAAAA;
        color: #212121;
        font-weight: normal
    }
</style>
<!-- include jquery and jquery-ui here -->
<script type="text/javascript">
    // This $(function()) block could be moved to another file. It's what I did.
    $(function() {
        var internal = 0;
        if (typeof SVG == 'undefined') SVG = {};
        if (typeof SVG.Weekpicker == 'undefined') SVG.Weekpicker = {};
            SVG.Weekpicker.GetWeek = function(_selectedDate) {
            var week = new Array();
                /* ***NOTE*** This is the only line required to "fix" Frictionless' code. */
                _selectedDate.setDate(_selectedDate.getDate()-_selectedDate.getDay());

            for (i = 0; i < 7; i++) {
                var tempDate = new Date(_selectedDate.getTime());
                tempDate.setDate(tempDate.getDate() + i);
                    week.push(tempDate.getTime());
                }
                return week;
            };
            SVG.Weekpicker.Init = function(selector) {
                var elem = $(selector);
                var insert = $('<input type="hidden" name="weekpicker'+(++internal)+'" value="'+elem.html()+'" />');
            SVG.Weekpicker._dates = SVG.Weekpicker.GetWeek(new Date());

                insert = insert.insertAfter(elem);
                insert.datepicker({
                beforeShowDay: function(_date) {
                if ($.inArray(_date.getTime(), SVG.Weekpicker._dates) >= 0)
                    return [true, "highlighted-week", "Week Range"];
                    return [true, "", ""];
                },
                onSelect: function(_selectedDate) {
                    var _date = new Date(_selectedDate);
                    SVG.Weekpicker._dates = SVG.Weekpicker.GetWeek(_date);

                    var start = new Date(SVG.Weekpicker._dates[0]);
                    var end = new Date(SVG.Weekpicker._dates[6]);

                    $(elem).html(($.datepicker.formatDate('MM d, yy', start, '')+' &mdash; '+$.datepicker.formatDate('MM d, yy', end, ''))+'&nbsp;&nbsp;');
                },
                showOn: "button",
                buttonImage: "/images/schedule.png",
                buttonImageOnly: false,
                showAnim: "slideDown",
            });
        };
    });

    $(document).ready(function() {
        // Attach a week picker to the weekpicker <span> tag.
        SVG.Weekpicker.Init("#weekpicker");
    }
</script>

<body>
    <span id="weekpicker"></span>
</body>
于 2011-07-18T20:25:18.847 に答える
1

トップアンサーに基づいてjQueryプラグインを作成しました。https://github.com/Prezent/jquery-weekpickerまたは Bower から入手してください。使用例:

$('#selector').weekpicker({
    startField: '#date-start',
    endField: '#date-end'
});
于 2014-02-21T06:54:15.597 に答える
1

スクリプトは、選択した日付から始まる 1 週間を強調表示します。

ここで実際の例を確認してください: http://jsfiddle.net/frictionless/W5GMg/

論理:

beforeShowDay : 表示されるカレンダーの日付ごとに実行されます。カレンダーの表示時、および特定の日付が選択されたときに呼び出されます。

onSelect : 関数は selectedDay から始まる選択された週をキャプチャし、 beforeShowDay は選択された週をレンダリングします

Jquery 1.5.1 および JQuery UI 1.8.1 で動作するスニペットを次に示します。

$(function () {
    var _dates=new Array();
    $('#datepicker').datepicker({
        beforeShowDay:function(_date){
            if($.inArray(_date.getTime(),_dates)>=0)
                return [true,"highlighted-week","Week Range"];
            return[true,"",""];
        },
        onSelect:function(_selectedDate){
            var _date=new Date(_selectedDate);
            _dates=new Array();
            for(i=0;i<7;i++){
                var tempDate=new Date(_date.getTime());
                tempDate.setDate(tempDate.getDate()+i);
                _dates.push(tempDate.getTime());
            }

        }
    });

});
于 2011-04-08T14:54:17.757 に答える
1

私は同じことをしようとしていましたが、入力フィールドに選択した週の範囲を表示することも望んでいました. datepicker beforeShow コールバックを使用して実際の日付に置き換えられます

    weekchooser = -> 
    $('#datepicker').datepicker({
        dateFormat: "M d, yy",
        altFormat:  "M d, yy",
        altField:       "#actualdate",
        selectWeek: true,
        firstDay:       1,
        showOtherMonths: true,
        selectOtherMonths: true,
        beforeShow: -> 
            $('#datepicker').val($('#actualdate').val())
        onClose: (date) ->
            reformatWeek(date)
            this.blur()
    }).click -> 
        currentDay = $('.ui-datepicker-current-day')
        currentDay.siblings().find('a').addClass('ui-state-active')

    calendarTR = $('.ui-datepicker .ui-datepicker-calendar tr');
    calendarTR.live 'mousemove', (event) ->
        $(this).find('td a').addClass('ui-state-hover');

    calendarTR.live 'mouseleave', (event) ->
        $(this).find('td a').removeClass('ui-state-hover');

    reformatWeek = (dateText) ->
        $('#datepicker').datepicker('refresh')
        current = parseInt($('.ui-datepicker-current-day').find('a').html())
        weekstart = parseInt($('.ui-datepicker-current-day').siblings().find('a').first().html())
        weekend     = parseInt($('.ui-datepicker-current-day').siblings().find('a').last().html())
        pattern = ///
            ^([a-zA-Z]+)\s+([0-9]{1,2})(,.*)
        ///
        [month, day, year] = dateText.match(pattern)[1..3]
        date = if weekstart > current
            first_month = relativeMonth(month, -1)
            "#{first_month} #{weekstart} - #{month} #{weekend}#{year}"
        else if weekend < current
            last_month = relativeMonth(month, 1)
            "#{month} #{weekstart} - #{last_month} #{weekend}#{year}"
        else
            "#{month} #{weekstart} - #{weekend}#{year}"
        $('#datepicker').val( date )

    relativeMonth = (month, c) -> 
        monthArray = $('#datepicker').datepicker('option', "monthNamesShort")
        index = monthArray.indexOf(month)
        if c > 0
            return if index + c > monthArray.length - 1 then monthArray[0] else monthArray[index + c]
        else
            return if index + c < 0 then monthArray[monthArray.length - 1] else monthArray[index + c]
于 2012-03-16T21:52:34.070 に答える
0

以下のリンクで回答済みの質問を確認できます

日ではなく週にjQuery UIカレンダー/日付ピッカーを使用するには?

$(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'); });

});

于 2014-10-08T06:36:18.660 に答える
0

複数のピッカー / 最後の jquery.ui で動作していません。この小さな書き直しを試してください:

jQuery(function() {
    var startDate; // closure
    var endDate;

    var baseAttachHandler = jQuery.datepicker._attachHandlers;
    jQuery.datepicker._attachHandlers = function(inst) {
            baseAttachHandler.apply(this, [inst]);

            var element_data = jQuery._data(inst.dpDiv.get(0));
            var ori_handler_mouseover = element_data.events.mouseover[0].handler;
            var ori_handler_mouseout = element_data.events.mouseout[0].handler;

            // remove handlers
            inst.dpDiv.undelegate("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a", 'mouseover');
            inst.dpDiv.undelegate("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a", 'mouseout');
            inst.dpDiv.undelegate("button, .ui-datepicker-prev, .ui-datepicker-next", 'mouseover');
            inst.dpDiv.undelegate("button, .ui-datepicker-prev, .ui-datepicker-next", 'mouseout');
            inst.dpDiv.find(".ui-datepicker-calendar tr").unbind('mouseover');
            inst.dpDiv.find(".ui-datepicker-calendar tr").unbind('mouseout');

            // attach proper ones
            if (this._get(inst, "weekSelector")) {
                inst.dpDiv.delegate("button, .ui-datepicker-prev, .ui-datepicker-next", 'mouseover', ori_handler_mouseover);
                inst.dpDiv.delegate("button, .ui-datepicker-prev, .ui-datepicker-next", 'mouseout', ori_handler_mouseout);
                inst.dpDiv.find(".ui-datepicker-calendar tr").bind('mouseover', function() { 
                    jQuery(this).find('td a').addClass('ui-state-hover');
                });
                inst.dpDiv.find(".ui-datepicker-calendar tr").bind('mouseout', function() { 
                    jQuery(this).find('td a').removeClass('ui-state-hover');
                });
            } else {
                inst.dpDiv.delegate("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a", 'mouseover', ori_handler_mouseover);
                inst.dpDiv.delegate("button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a", 'mouseout', ori_handler_mouseout);
            }
        };

    jQuery.datepicker.calcWeekBoundaries = function () {
        var date = jQuery(this).datepicker('getDate');
        if (date) {
            var tmp = date.getDay();
            if (tmp == 0) { // starting with monday, i'm italian ;-)
                endDate = date;
                startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 6);
            } else {
                startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - tmp + 1);
                endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - tmp + 7);
            }
        }
    };

    jQuery("#yourcontrol").datepicker(
        jQuery.extend({}, jQuery.datepicker.regional["yourlanguage"], {
            showOtherMonths: true
            , selectOtherMonths: true
            , changeMonth: true
            , changeYear: true
            , onSelect: function(dateText, inst) { 
                if (jQuery.datepicker._get(inst, "weekSelector")) {
                    jQuery.datepicker.calcWeekBoundaries.apply(this, []);
                    jQuery(this).datepicker('setDate', startDate);
                }
                inst.input.trigger("change");
            }
            , beforeShowDay: function(date) {
                var inst = jQuery.data(this, "datepicker");
                var cssClass = '';
                if (jQuery.datepicker._get(inst, "weekSelector") && date) {
                    if(date >= startDate && date <= endDate) {
                        cssClass = 'ui-state-active';
                    }
                }
                return [true, cssClass];
            }
            , beforeShow: function(input, inst) {
                jQuery.datepicker.calcWeekBoundaries.apply(this, []);
            }
            , weekSelector: true // the magic is here
        })
    );
});
于 2015-12-12T23:01:58.143 に答える