【问题标题】:Jquery Datepicker - Autofill date based on first date without selectJquery Datepicker - 基于第一个日期自动填充日期而不选择
【发布时间】:2020-04-27 20:02:25
【问题描述】:

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

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

有什么建议吗?

这是代码

$(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>

注意

第一个 datepicker 最小日期是从明天开始,maxdate 是 3 天 其中不包括假期和周日,而第二个 datepicker mindate 是 基于第一个 datepicker 日期,maxdate 为 7 天,不包括 节假日和周日。我只想显示最后的第三个和第七个日期 日期选择器输入而不选择它们。两个输入都不应该 可供选择(只读)。

【问题讨论】:

  • 您能否举例说明“在 datepicker1 中设置第三个日期并在 datepicker 2 中设置第七个日期而不选择它们(自动)”?
  • 是的。第一个 datepicker 最小日期是从明天开始,maxdate 是 3 天,不包括节假日和星期日,而第二个 datepicker mindate 是基于第一个 datepicker 日期,maxdate 是 7 天,不包括节假日和星期日。我只想在日期选择器输入中显示最后的第 3 和第 7 日期而不选择它们。两个输入都不应该可供选择(只读)。
  • 那么第一个 Datepicker 的值应该是 14th Jan(从今天开始的第 3 个),第二个 Datepicker 的值应该是 22nd Jan(从 14 日开始,7 个工作日)?
  • @MayankPatel 是的,但是因为我在数组中添加了 1 月 15 日和 18 日作为假期,所以它将跳过那些日子,而 1 月 24 日假设是第二个日期选择器的第 7 天。
  • 您不希望节假日和星期日将删除 15 日、18 日和 19 日。从第一个 datepicker-14th 开始,第 7 天怎么会是 1 月 24 日?现在是 23 日。对吗?

标签: javascript jquery laravel datepicker


【解决方案1】:

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

对于这个代码,它类似于我给你的其他代码。只是当涉及到一个部门中的日期选择器时,它是不同的。但是,我在代码中对此进行了注释。对于第三个日期选择器,我在为第一个日期选择器运行第一个 maxDate 函数时编写该日期选择器,然后在运行第二个日期选择器函数 maxDate 函数时编写该日期选择器。由于您不希望用户对第三个日期选择器做任何事情,除了看到它,我使用除法而不是输入字段作为第三个日期选择器的占位符。他们仍然可以选择日期,但它不会做任何事情。您可能可以为这些日期添加样式,使其看起来它们的选定和未选定状态是相同的。此外,还可以添加工具提示。

对于这个答案,我也给你两个版本。第二个版本优化得更好,更灵活。版本 1 和 2 是相同的代码。尽管如此,第二个版本将 3 个日期选择器的 jQuery 对象分配给 3 个变量,这样每次需要使用这些分区时,它不会导致 jQuery 再次查找这些分区对象。此外,您可以更轻松地从一处更改其命名上下文。

尝试选择第一天,您会看到日期会动态变化。此外,如果您参考我的任何答案并发现其中的任何错误,请随时通知我评论中的错误。谢谢。

版本 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>

【讨论】:

  • 该死的,这真的像魅力!非常感谢兄弟:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多