jQuery Bootstrap datepicker:选择整周并在输入字段中输入周间隔

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28713964/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:31:06  来源:igfitidea点击:

Bootstrap datepicker: Select entire week and put week interval in input field

jquerybootstrap-datepicker

提问by Rafael code

I am currently using bootstrap-datepicker (https://github.com/eternicode/bootstrap-datepicker), but want to be able to select entire weeks in the calendar (Monday to Sunday), as well as display the week interval in the input field that I am selecting from. The default interval in the input field should be the week that you are currently in.

我目前正在使用 bootstrap-datepicker ( https://github.com/eternicode/bootstrap-datepicker),但希望能够在日历中选择整周(周一至周日),并在我从中选择的输入字段。输入字段中的默认间隔应该是您当前所在的那一周。

I have seen a somewhat similar method using jQuery UI to display the interval on jsfiddle.

我见过使用 jQuery UI 在jsfiddle上显示间隔的有点类似的方法。

C

I have tried editing this code to work for bootstrap-datepicker, without any luck.

我尝试编辑此代码以适用于 bootstrap-datepicker,但没有任何运气。

Any idea how I can implement this for bootstrap-datepicker? : The steps are outlined in this image

知道如何为 bootstrap-datepicker 实现这个吗?: 此图中概述了步骤

Any help is highly appreciated!

任何帮助表示高度赞赏!

回答by Prakash Thete

I have used Bootstrap datetime picker in my project ran into same problem like yours When trying to select the weeks.

我在我的项目中使用了 Bootstrap 日期时间选择器,在尝试选择周时遇到了和你一样的问题。

Got the below Solution on my own you can try it.

我自己得到了以下解决方案,您可以尝试一下。

Required Files :

所需文件:

  1. Bootstrap.css
  2. Bootstrapdatetime picker css(You can use only datepicker instead of datetime)
  3. jquery.js
  4. Bootstrap.js
  5. moment.js
  6. Bootstrap Date time Picker js(Again you can use only datepicker instead of datetime)
  1. Bootstrap.css
  2. Bootstrapdatetime 选择器 css(你只能使用 datepicker 而不是 datetime)
  3. jquery.js
  4. Bootstrap.js
  5. 时刻.js
  6. Bootstrap 日期时间选择器 js(同样,您只能使用日期选择器而不是日期时间)

HTML :

HTML :

<div class="container">    
    <div class="row">
        <div class="col-sm-6 form-group">
            <div class="input-group" id="DateDemo">
              <input type='text' id='weeklyDatePicker' placeholder="Select Week" />
            </div>
        </div>
    </div>
</div>

JS :Used the moment.js for calculating the start and end of the week.

JS :使用 moment.js 来计算一周的开始和结束。

//Initialize the datePicker(I have taken format as mm-dd-yyyy, you can have your own)
$("#weeklyDatePicker").datetimepicker({
    format: 'MM-DD-YYYY'
});

//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
    value = $("#weeklyDatePicker").val();
    firstDate = moment(value, "MM-DD-YYYY").day(0).format("MM-DD-YYYY");
    lastDate =  moment(value, "MM-DD-YYYY").day(6).format("MM-DD-YYYY");
    $("#weeklyDatePicker").val(firstDate + "   -   " + lastDate);
});

CSS :

CSS :

.bootstrap-datetimepicker-widget tr:hover {
    background-color: #808080;
}

Link to Working Code in JSFiddle :

链接到 JSFiddle 中的工作代码:

https://jsfiddle.net/Prakash_Thete/9usq3enn/

https://jsfiddle.net/Prakash_Thete/9usq3enn/

回答by IamMHussain

I have optimized the above mentioned examples.

我已经优化了上面提到的例子。

HTML

HTML

<div class="container">    
   <div class="row">
       <div class="col-sm-6 form-group">
           <div class="input-group" id="DateDemo">
               <input type='text' id='weeklyDatePicker' placeholder="Select Week" />
           </div>
       </div>
   </div>
</div>

JS

JS

$(document).ready(function(){
    moment.locale('en', {
      week: { dow: 1 } // Monday is the first day of the week
    });

  //Initialize the datePicker(I have taken format as mm-dd-yyyy, you can     //have your owh)
  $("#weeklyDatePicker").datetimepicker({
      format: 'MM-DD-YYYY'
  });

   //Get the value of Start and End of Week
  $('#weeklyDatePicker').on('dp.change', function (e) {
      var value = $("#weeklyDatePicker").val();
      var firstDate = moment(value, "MM-DD-YYYY").day(0).format("MM-DD-YYYY");
      var lastDate =  moment(value, "MM-DD-YYYY").day(6).format("MM-DD-YYYY");
      $("#weeklyDatePicker").val(firstDate + " - " + lastDate);
  });
});

CSS

CSS

.bootstrap-datetimepicker-widget .datepicker-days table tbody tr:hover {
    background-color: #eee;
}

Check the link for demo: https://jsfiddle.net/IamMHussain/ozdrdbqf/1/

检查演示链接:https: //jsfiddle.net/IamMHussain/ozddrdbqf/1/

回答by rtw

I am currently working on a project with the same requirement. Don't know where I found it, but this fiddle on http://codepen.io/chanduvkm/pen/yeXKGWaddresses almost the same issue in a slightly different way, but using the bootstrap-datepicker library you are currently using. The default value could be easily added. However, the CSS of the active week fails when the option 'weekStart: 1' is set, which is what I actually need (ISO-8601 week starts on Monday).

我目前正在从事具有相同要求的项目。不知道我在哪里找到的,但是http://codepen.io/chanduvkm/pen/yeXKGW上的这个小提琴以略有不同的方式解决了几乎相同的问题,但使用的是您当前使用的 bootstrap-datepicker 库。可以轻松添加默认值。但是,当设置了选项 'weekStart: 1' 时,活动周的 CSS 会失败,这正是我真正需要的(ISO-8601 周从星期一开始)。

    var startDate,
    endDate;

  $('#weekpicker').datepicker({
    autoclose: true,
    format :'mm/dd/yyyy',
    forceParse :false
}).on("changeDate", function(e) {
    //console.log(e.date);
    var date = e.date;
    startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay());
    endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay()+6);
    //$('#weekpicker').datepicker("setDate", startDate);
    $('#weekpicker').datepicker('update', startDate);
    $('#weekpicker').val((startDate.getMonth() + 1) + '/' + startDate.getDate() + '/' +  startDate.getFullYear() + ' - ' + (endDate.getMonth() + 1) + '/' + endDate.getDate() + '/' +  endDate.getFullYear());
});

In response to the previous answer by prakash, I forked the fiddle to start on Monday: https://jsfiddle.net/skfw0k53/by adding the following:

为了回应 prakash 的先前回答,我将小提琴分叉到星期一开始:https://jsfiddle.net/skfw0k53/添加以下内容:

    moment.locale('en', {
  week: { dow: 1 } // Monday is the first day of the week
});

So, basically two different libs to approach the problem.

所以,基本上是两个不同的库来解决这个问题。

回答by Shiva Manhar

You can try it.

你可以试试看。

Required file:

所需文件:

jquery-1.11.3.js
bootstrap-datepicker.min.js
bootstrap-datepicker.css
bootstrap.min.css

jQuery的1.11.3.js
引导-datepicker.min.js
引导,datepicker.css
bootstrap.min.css

HTML

HTML

<div class="container">
  <div class="row">
      <div class='col-md-3'>
    Week Start <select id="cweek">
      <option value='0'> 0 </option>
      <option value='1'> 1 </option>
      <option value='2'> 2 </option>
      <option value='3'> 3 </option>
      <option value='4'> 4 </option>
      <option value='5'> 5 </option>
      <option value='6'> 6 </option>
      <option value='7'> 7 </option>
    </select>
  </div>
  <div class='col-md-3'>
    Copy <select name='cweek_number' id='cweek_number'>
      <option value='1'> 1 Week </option>
      <option value='2'> 2 Week </option>
      <option value='3'> 3 Week </option>
      <option value='4'> 4 Week </option>
    </select> from
  </div>
</div>
</div>
<div class="container">
  <div class="row">


      <div class="from_cal"></div>
      </div>
      <div class="row">



      <div class="to_cal"></div>
    </div>
  </div>
</div>

js

js

var weekOfStart = 0;
      var startDate;
      var endDate;
      var toCal_startDate;
      var toCal_endDate;
      var setNumberOfWeek = 1;

      var from_cal = '.from_cal';
      var to_cal = '.to_cal';

      var obj =   $(from_cal).datepicker({
                  weekStart:weekOfStart,
                  maxViewMode: 0,
                  onSelect: function (date) {

                  },
                  beforeShowDay: function(date)
                  {
                    var cssClass = '';
                      if(date >= startDate && date <= endDate)
                          cssClass = 'oui-state-hover';
                      return [true, cssClass];
                  }
              //    startDate: new Date()
        });


      $(from_cal).on('changeDate', function(evt) {
          var date = evt.date;
          var dayAdjustment = date.getDay() - weekOfStart;
          if (dayAdjustment < 0) {
              dayAdjustment += 7;
          }
          if(setNumberOfWeek > 1)
          {
            weekLast = 7*(setNumberOfWeek-1);
          }
          else {
            weekLast = 0;
          }
          startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment);
          endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment + (6+weekLast));

          // console.log(startDate);
          // console.log(endDate);

          $(this).find('.active').closest('tr').addClass('oui-selected');
          if(setNumberOfWeek > 1)
          {
            $(this).find('.active').closest('tr').nextAll().slice(0, (setNumberOfWeek-1)).addClass('oui-selected');
          }
      });

        $(from_cal).on('mousemove', '.table-condensed tr', function () {
            $(this).find('td').addClass('oui-state-hover');
            if(setNumberOfWeek > 1)
            {

            $(this).nextAll().slice(0, (setNumberOfWeek-1)).find('td').addClass('oui-state-hover');
            }

        });
        $(from_cal).on('mouseleave', '.table-condensed tr', function () {

              $(this).find('td').removeClass('oui-state-hover');

              $(this).nextAll().find('td').removeClass('oui-state-hover');

        });


        $(from_cal).find('td').on('click', function(){

          console.log('ok');
        });

    obj.datepicker();


// To date Calendar  code

        var toCalObj =   $(to_cal).datepicker({
                      weekStart:weekOfStart,
                      maxViewMode: 0,
                  //    startDate: new Date()
        });
        toCalObj.datepicker();
        $(to_cal).on('mousemove', '.table-condensed tr', function () {
            $(this).find('td').addClass('kui-state-hover');
            if(setNumberOfWeek > 1)
            {

            $(this).nextAll().slice(0, (setNumberOfWeek-1)).find('td').addClass('kui-state-hover');
            }

        });
        $(to_cal).on('mouseleave', '.table-condensed tr', function () {

              $(this).find('td').removeClass('kui-state-hover');

              $(this).nextAll().find('td').removeClass('kui-state-hover');

        });

        $(to_cal).on('changeDate', function(evt) {

            var date = evt.date;
            var dayAdjustment = date.getDay() - weekOfStart;
            if (dayAdjustment < 0) {
                dayAdjustment += 7;
            }
            if(setNumberOfWeek > 1)
            {
              weekLast = 7*(setNumberOfWeek-1);
            }
            else {
              weekLast = 0;
            }
            toCal_startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment);
            toCal_endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - dayAdjustment + (6+weekLast));

            console.log(toCal_startDate);
            console.log(toCal_endDate);

            $(this).find('.active').closest('tr').addClass('oui-selected');
            if(setNumberOfWeek > 1)
            {
              $(this).find('.active').closest('tr').nextAll().slice(0, (setNumberOfWeek-1)).addClass('oui-selected');
            }

          //  console.log(date.getDay());
        });


//comman code

      $('#cweek').change(function()
    {
      weekOfStart =  $('#cweek').val();
      obj.datepicker('destroy');
      toCalObj.datepicker('destroy');
      obj.datepicker({weekStart:$('#cweek').val(),maxViewMode:0}).datepicker('update');
      toCalObj.datepicker({weekStart:$('#cweek').val(),maxViewMode:0}).datepicker('update');
    });

    $('#cweek_number').change(function()
    {
      setNumberOfWeek = $('#cweek_number').val();
      obj.datepicker('destroy');
      toCalObj.datepicker('destroy');
      obj.datepicker({weekStart:$('#cweek').val(),maxViewMode:0}).datepicker('update');
      toCalObj.datepicker({weekStart:$('#cweek').val(),maxViewMode:0}).datepicker('update');

    });


    $('.table-condensed').addClass('table');

Screen Shot

截屏

enter image description here

在此处输入图片说明

JSFiddle link https://jsfiddle.net/shivamanhar/ddphp8jx/9/

JSFiddle 链接https://jsfiddle.net/shivamanhar/ddphp8jx/9/

回答by user4529914

A very quick solution: 1. Modify JS file: bootstrap-datepicker.js 2. Modify CSS file: bootstrap-datepicker3.css 3. Modify your code.

一个非常快速的解决方案: 1. 修改 JS 文件:bootstrap-datepicker.js 2. 修改 CSS 文件:bootstrap-datepicker3.css 3. 修改你的代码。

        //Modifications on bootstrap-datepicker.js
        //-----
        if (!target.hasClass('disabled')){
                // Clicked on a day
                if (target.hasClass('day')){
                        day = parseInt(target.text(), 10) || 1;
                        year = this.viewDate.getUTCFullYear();
                        month = this.viewDate.getUTCMonth();
                        //HF[+][i]201612151500
                        datepickerPlugin.actualWeek = $(target[0].parentNode).find('.cw').text();
                        //HF[+][f]201612151500
                        // From last month
                        if (target.hasClass('old')){
                                if (month === 0) {
                                        month = 11;
                                        year = year - 1;
                                        monthChanged = true;
                                        yearChanged = true;
                                } else {
                                        month = month - 1;
                                        monthChanged = true;
                                }
                        }
        //-----
        //HF[-][i]201612151500
        //   validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g,
        //HF[-][f]201612151500
        //HF[+][i]201612151500
        validParts: /ww?|dd?|DD?|mm?|MM?|yy(?:yy)?/g,
        //HF[+][f]201612151500
        nonpunctuation: /[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g,
        parseFormat: function(format){
                if (typeof format.toValue === 'function' && typeof format.toDisplay === 'function')
                        return format;
                // IE treats 
        .datepicker tbody tr:hover {
         background-color: #eee;
        }
        .datepicker tbody tr:hover td,
        .datepicker tbody tr td.active {
         border-radius: 0;
        }
        .datepicker tbody tr:hover td:last-child,
        .datepicker tbody tr td.active:last-child {
         border-radius: 0 3px 3px 0;
        }
        .datepicker tbody tr:hover td:first-child,
        .datepicker tbody tr  td.active:nth-child(2) {
         border-radius: 3px 0 0 3px;
        }
as a string end in inputs (truncating the value), // so it's a bad format delimiter, anyway var separators = format.replace(this.validParts, '
        <!--RefLinks-->
        <link href="~/libraries/bootstrap-datepicker-1.6.4/css/bootstrap-datepicker3.css" rel="stylesheet">
        <script src="~/libraries/bootstrap-datepicker-1.6.4/js/bootstrap-datepicker.js"></script>
 
        <!--OnBody-->
        <input id="datepicker2" class="datepicker4" style="width: 300px;" type="text">

        <!--OnScriptSection-->
        $(function ()
        {
            var $weekPicker = $("#datepicker2");
            $weekPicker.datepicker
                (
                    {
                        autoclose: true,
                        format: 'ww', //'dd-M-yyyy',
                        calendarWeeks: true,
                        //maxViewMode: 0,
                        weekStart: 1
                    }
                )        
').split('##代码##'), parts = format.match(this.validParts); if (!separators || !separators.length || !parts || parts.length === 0){ throw new Error("Invalid date format."); } return {separators: separators, parts: parts}; }, //----- formatDate: function(date, format, language){ if (!date) return ''; if (typeof format === 'string') format = DPGlobal.parseFormat(format); if (format.toDisplay) return format.toDisplay(date, format, language); var val = { //HF[+][i]201612151500 ww: 'Semana ' + datepickerPlugin.actualWeek.toString(), //HF[+][f]201612151500 d: date.getUTCDate(), D: dates[language].daysShort[date.getUTCDay()], DD: dates[language].days[date.getUTCDay()], m: date.getUTCMonth() + 1, M: dates[language].monthsShort[date.getUTCMonth()], MM: dates[language].months[date.getUTCMonth()], yy: date.getUTCFullYear().toString().substring(2), yyyy: date.getUTCFullYear() }; val.dd = (val.d < 10 ? '0' : '') + val.d; val.mm = (val.m < 10 ? '0' : '') + val.m; date = []; var seps = $.extend([], format.separators); for (var i=0, cnt = format.parts.length; i <= cnt; i++){ if (seps.length) date.push(seps.shift()); date.push(val[format.parts[i]]); } return date.join(''); }, //-----
##代码## ##代码##