jQuery Datepicker-基于第一个日期的自动填充日期,无需选择 [英] Jquery Datepicker - Autofill date based on first date without select

查看:90
本文介绍了jQuery Datepicker-基于第一个日期的自动填充日期,无需选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面我有一个2个日期选择器,用户必须选择它们,然后 第二个datepicker将根据datepicker1更改最小日期 但我的目标是在datepicker1中设置第3个日期,并在datepicker1中设置第7个日期 datepicker 2而不选择它们(自动).

Below i have a 2 datepicker which user have to select them and then the 2nd datepicker will change the min date according to datepicker1 but my goal is to set the 3rd date in datepicker1 and set 7th date in datepicker 2 without selecting them(Auto).

到目前为止,我可以显示第一个日期选择器,最后一个可用 天(第3个日期),而我仍无法达到第2个日期 datepicker(7th):(

So far i can able to display the first datepicker with last available day(3rd date) while i still can't achieve the dates for 2nd datepicker(7th) :(

有任何建议吗?

Any suggestion?

这是代码

$(document).ready(function() { 
    var array = ["15-01-2020","18-01-2020"];
   
    function includeDate(date) {
        var dateStr = jQuery.datepicker.formatDate('dd-mm-yy', date);
        // Date 0 = Sunday & 6 = Saturday
        return date.getDay() !== 0 && array.indexOf(dateStr) === -1;
    }

    function getTomorrow(date) {
        return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
    }
    
   

    $('#datepicker1').datepicker(
        {
      defaultDate: "+1d",
      inline: true,
      showOtherMonths: true,
      changeMonth: true,
      selectOtherMonths: true,
      required: true,
      showOn: "focus",
      numberOfMonths: 1,
      minDate: 1,
      
    beforeShowDay: function(date) {
        return [includeDate(date)];
    },
    maxDate: (function(max) {
        var nextAvailable = new Date();
        var count = 0;
        var extra = 0;
        while(count < max) {
            nextAvailable = getTomorrow(nextAvailable);             
            if ( !includeDate(nextAvailable) ) {
                extra++;  
            } else {
                count++;
            }            
        }
        return max + extra;
    })
    (3)   
});
    $('#datepicker1').change(function () {
        var from = $('#datepicker1').datepicker('getDate');
        // Date diff can be obtained like this without needing to parse a date string.
        var date_diff = Math.ceil((from - new Date()) / 86400000);
        
        $('#datepicker2').val('').datepicker({
            inline: true,
      showOtherMonths: true,
      changeMonth: true,
      selectOtherMonths: true,
      required: true,
      showOn: "focus",
      numberOfMonths: 1,
      minDate: date_diff + 1,
    beforeShowDay: function(date) {
      return [includeDate(date)];
    },
    
    maxDate: (function(max) {
        var nextAvailable = $('#datepicker1').datepicker('getDate');
        var count = 0;
        var extra = 0;
        while(count < max) {
            nextAvailable = getTomorrow(nextAvailable);             
            if ( !includeDate(nextAvailable) ) {
                extra++;
            } else {
                count++;
            }            
        }

        return max + date_diff + extra;
    })
    (7)
}); 
    });
   $( "#datepicker1" ).datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date()+100);
});

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<p>datepicker1 <input id="datepicker1"></p>
<p>datepicker2 <input id="datepicker2"></p>

注意

第一个日期选择器的最小日期是明天,最大日期是3天 其中不包括节假日和星期日,而第二个日期选择器介意是 基于第1个日期选择器日期,最大日期为7天,其中不包括 假期和周日.我只想显示最后的第3和第7个日期 datepicker输入但不选择它们 可供选择(只读).

The first datepicker min date is from tomorrow and maxdate is 3 days which exclude holidays and sundays while the 2nd datepicker mindate is based on 1st datepicker date and maxdate is 7 days which exclude holidays and sundays. I just want the last 3rd and 7th date display in the datepicker input without selecting them.Both input should not available for choosing(Read-Only).

推荐答案

已更新:起初,我认为答案代码存在错误(我没有真正看过),从上一个答案中为您提供.但是,在再次浏览旧代码之后,我意识到旧代码没有错误,因为每次对日期选择器对象进行初始化时,datepicker类都会被删除.因此,我更新了此答案以反映这一点.

Updated: At first, I thought there was a bug with the answer code(I didn't really look at it) I provided you from the previous answer. But after looking through the old code again, I realized there isn't a bug with the old code since the datepicker class get remove every time the date picker object get initialize. Thus, I updated this answer to reflect that.

对于此代码,它与我给您的其他代码相似.只是在部门中选择日期选择器时有所不同.但是,我将其注释为代码.对于第三个日期选择器,当第一个maxDate函数针对第一个日期选择器运行时,然后针对第二个日期选择器函数maxDate函数运行时,我组成该日期选择器.由于除了看到它之外,您不希望用户对第三种日期选择器执行任何操作,因此我使用了除法而不是输入字段作为第三种日期选择器的占位符.他们仍然可以选择日期,但不会执行任何操作.您可能可以为这些日期添加样式,以使其选择状态和未选择状态看起来相同.另外,可以添加工具提示.

For this code, it is similar to the other code I gave you. It just that when it come to datepicker in a division it is different. However, I commented that into code. For the third datepicker, I compose that datepicker when the first maxDate function run for the first datepicker, then against when the second date picker function maxDate function is run. Since you don't want the user to do anything with the third datepicker, except seeing it, I used a division instead of an input field as a place holder for the third datepicker. They can still select the date but it will not do anything. You probably can add style to those dates to make it seem their selected and unselected states are the same. Also, tool tips can be added.

对于这个答案,我也给你两个版本.第二个版本进行了更好的优化和更灵活.版本1和2是相同的代码.但是,第二个版本将3个datepickers的jQuery对象分配给3个变量,以便每次需要使用这些划分时,它都不会导致jQuery再次查找这些划分对象.而且,您更容易从一个地方更改其命名上下文.

For this answer, I also give you two versions. The second version is better optimized and more flexible. Version 1 and 2 are the same code. Nonetheless, the second version assign the jQuery object of the 3 datepickers to 3 variables so that every time those divisions is needed to be used, it does not cause jQuery to look up those division objects again. Also, it is easier for you to change their naming context from one place.

尝试选择第一天,您会看到日子会动态变化.另外,如果您参考我的任何答案并找到其中的任何错误,请随时在评论中通知我这些错误.谢谢.

Try to play around selecting the first day and you will see the days will dynamically change. Also, if you refer to any of my answer and find any bugs with in them, feel free to notify me of the bugs in the comment. Thank you.

版本1:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script>
$(document).ready(function() { 
    var array = ["15-01-2020","18-01-2020"];
    // Store date for datepicker3 here
    var dp3 = [];
   
    function includeDate(date) {
        var dateStr = jQuery.datepicker.formatDate('dd-mm-yy', date);
        // Date 0 = Sunday & 6 = Saturday
        return date.getDay() !== 0 && array.indexOf(dateStr) === -1;
    }

    function getTomorrow(date) {
        return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
    }

    function dp2ini () {
        var from = $('#datepicker1').datepicker('getDate');
        // Date diff can be obtained like this without needing to parse a date string.
        var date_diff = Math.ceil((from - new Date()) / 86400000);
        
        /* 
         * For an input field, the hasDatepicker class have to removed
         * for the options to take effect if re-initialize. This, can
         * also be done with the destroy option of datepicker
         * $('#datepicker2').datepicker("destroy"). However, it seem, 
         * removing its class is faster in this case.
         *
         * On the other hand if a datepicker widget is a part
         * or a division, it has to be destroy as the html
         * for the widget is placed as html content inside that division,
         * and simply just removing the hasDatepicker class from that division
         * will cause the reinitializer to write in a second datepicker widget.
         * 
         * In a division where it only contained the picker 
         * object, it is faster to just set the HTML to blank
         * and remove the hasDatepicker class. On the otherhand,
         * for more complicated division, it is better to use,
         * the destroy option from "datepicker".
         */
        $('#datepicker2').val('').removeClass("hasDatepicker");
        
        $('#datepicker2').datepicker({
            inline: true,
            showOtherMonths: true,
            changeMonth: true,
            selectOtherMonths: true,
            required: true,
            showOn: "focus",
            numberOfMonths: 1,
            minDate: date_diff + 1,
          beforeShowDay: function(date) {
            return [includeDate(date)];
          },
    
          maxDate: (function(max) {
              var nextAvailable = $('#datepicker1').datepicker('getDate');
              
              var count = 0;
              var extra = 0;
              while(count < max) {
                  nextAvailable = getTomorrow(nextAvailable);             
                  if ( !includeDate(nextAvailable) ) {
                      extra++;
                  } else {
                      count++;
                  }            
              }

              dp3[1] = new Date();
              dp3[1].setDate( dp3[1].getDate() + max + date_diff + extra );
              dp3[1] = dp3[1].toDateString();
        
              // Destroy dp3 and re-initalize it.
              //$('#datepicker3').datepicker("destroy"); 
              
              $('#datepicker3').empty();
              $('#datepicker3').removeClass("hasDatepicker");
              
              $( "#datepicker3" ).datepicker({
                  maxDate: max + date_diff + extra,
                beforeShowDay: function(date){
                    return [date.toDateString() == dp3[0] 
                         || date.toDateString() == dp3[1]
                           ];
                }
              });

              return max + date_diff + extra;
          })(7)
        });
    }
    
    $('#datepicker1').datepicker({
      defaultDate: "+1d",
      inline: true,
      showOtherMonths: true,
      changeMonth: true,
      selectOtherMonths: true,
      required: true,
      showOn: "focus",
      numberOfMonths: 1,
      minDate: 1,
    
    beforeShowDay: function(date) {
        return [includeDate(date)];
    },
    
    maxDate: (function(max) {
        var nextAvailable = new Date();        
        var count = 0;
        var extra = 0;
        while(count < max) {
            nextAvailable = getTomorrow(nextAvailable);             
            if ( !includeDate(nextAvailable) ) {
                extra++;  
            } else {
                count++;
            }            
        }
        
        /* Initialize datepicker 3 here. */
        // NOTE: If dp1 needed to be reinitialize dp3
        //       also have to be destroyed and reinitialize.
        
        // The last day will always be a pick-able one...
        // Because if it wasn't another day would had been added to it.
        dp3[0] = new Date();
        dp3[0].setDate( dp3[0].getDate() + max + extra );
        dp3[0] = dp3[0].toDateString();
        
        $( "#datepicker3" ).datepicker({
          maxDate: max + extra,
          beforeShowDay: function(date){
            return [date.toDateString() == dp3[0]];
          }
        
        });

        return max + extra;
    })
    (3)   
});

  $( "#datepicker1" ).change(dp2ini);
  // Also trigger the change event.
  $( "#datepicker1" ).datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date()+100).trigger("change");
});

</script>

<p>datepicker1 <input id="datepicker1"></p>
<p>datepicker2 <input id="datepicker2"></p>
<div id="datepicker3"></div>

版本2:

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<script>
$(document).ready(function() { 
    var array = ["15-01-2020","18-01-2020"];
    // Store date for datepicker3 here
    var dp3 = [];
    var datepicker1 = $('#datepicker1')
        datepicker2 = $('#datepicker2'),
        datepicker3 = $('#datepicker3');
   
    function includeDate(date) {
        var dateStr = jQuery.datepicker.formatDate('dd-mm-yy', date);
        // Date 0 = Sunday & 6 = Saturday
        return date.getDay() !== 0 && array.indexOf(dateStr) === -1;
    }

    function getTomorrow(date) {
        return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1);
    }

    function dp2ini () {
        var from = datepicker1.datepicker('getDate');
        // Date diff can be obtained like this without needing to parse a date string.
        var date_diff = Math.ceil((from - new Date()) / 86400000);
        
        /* 
         * For an input field, the hasDatepicker class have to removed
         * for the options to take effect if re-initialize. This, can
         * also be done with the destroy option of datepicker
         * $('#datepicker2').datepicker("destroy"). However, it seem, 
         * removing its class is faster in this case.
         *
         * On the other hand if a datepicker widget is a part
         * or a division, it has to be destroy as the html
         * for the widget is placed as html content inside that division,
         * and simply just removing the hasDatepicker class from that division
         * will cause the reinitializer to write in a second datepicker widget.
         * 
         * In a division where it only contained the picker 
         * object, it is faster to just set the HTML to blank
         * and remove the hasDatepicker class. On the otherhand,
         * for more complicated division, it is better to use,
         * the destroy option from "datepicker".
         */
        datepicker2.val('').removeClass("hasDatepicker");
        
        datepicker2.datepicker({
            inline: true,
            showOtherMonths: true,
            changeMonth: true,
            selectOtherMonths: true,
            required: true,
            showOn: "focus",
            numberOfMonths: 1,
            minDate: date_diff + 1,
          beforeShowDay: function(date) {
            return [includeDate(date)];
          },
    
          maxDate: (function(max) {
              var nextAvailable = datepicker1.datepicker('getDate');
              
              var count = 0;
              var extra = 0;
              while(count < max) {
                  nextAvailable = getTomorrow(nextAvailable);             
                  if ( !includeDate(nextAvailable) ) {
                      extra++;
                  } else {
                      count++;
                  }            
              }

              dp3[1] = new Date();
              dp3[1].setDate( dp3[1].getDate() + max + date_diff + extra );
              dp3[1] = dp3[1].toDateString();
        
              // Destroy dp3 and re-initalize it.
              //$('#datepicker3').datepicker("destroy"); 
              
              datepicker3.empty();
              datepicker3.removeClass("hasDatepicker");
              
              datepicker3.datepicker({
                  maxDate: max + date_diff + extra,
                beforeShowDay: function(date){
                    return [date.toDateString() == dp3[0] 
                         || date.toDateString() == dp3[1]
                           ];
                }
              });

              return max + date_diff + extra;
          })(7)
        });
    }
    
    datepicker1.datepicker({
      defaultDate: "+1d",
      inline: true,
      showOtherMonths: true,
      changeMonth: true,
      selectOtherMonths: true,
      required: true,
      showOn: "focus",
      numberOfMonths: 1,
      minDate: 1,
    
    beforeShowDay: function(date) {
        return [includeDate(date)];
    },
    
    maxDate: (function(max) {
        var nextAvailable = new Date();        
        var count = 0;
        var extra = 0;
        while(count < max) {
            nextAvailable = getTomorrow(nextAvailable);             
            if ( !includeDate(nextAvailable) ) {
                extra++;  
            } else {
                count++;
            }            
        }
        
        /* Initialize datepicker 3 here. */
        // NOTE: If dp1 needed to be reinitialize dp3
        //       also have to be destroyed and reinitialize.
        
        // The last day will always be a pick-able one...
        // Because if it wasn't another day would had been added to it.
        dp3[0] = new Date();
        dp3[0].setDate( dp3[0].getDate() + max + extra );
        dp3[0] = dp3[0].toDateString();
        
        datepicker3.datepicker({
          maxDate: max + extra,
          beforeShowDay: function(date){
            return [date.toDateString() == dp3[0]];
          }
        
        });

        return max + extra;
    })
    (3)   
});

  datepicker1.change(dp2ini);
  // Also trigger the change event.
  datepicker1.datepicker({ dateFormat: "yy-mm-dd"}).datepicker("setDate", new Date()+100).trigger("change");
});

</script>

<p>datepicker1 <input id="datepicker1"></p>
<p>datepicker2 <input id="datepicker2"></p>
<div id="datepicker3"></div>

这篇关于jQuery Datepicker-基于第一个日期的自动填充日期,无需选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆