【问题标题】:JQuery datepicker default date and multiple datepickersJQuery datepicker 默认日期和多个 datepicker
【发布时间】:2020-04-10 01:55:06
【问题描述】:

我正在使用这个日期选择器 https://jqueryui.com/datepicker/

我在同一个 html 表单中有 2 个日期字段。 我需要将今天加载的第一个字段作为默认日期。 第二个是今天的日期 -7(1 周前)。

由于某种原因无法正常工作。 我可以让两个字段都正常工作,但它们不会加载任何默认日期。

感谢任何帮助。


 $(function() {   
       $( "#from" ).datepicker({   
      defaultDate: "+1w",  
      changeMonth: true,   
      numberOfMonths: 1,  
      onClose: function( selectedDate ) {  
        $( "#to" ).datepicker( "option", "minDate", selectedDate );  
      }  
    });  
    $( "#to" ).datepicker({
      defaultDate: "+1w",
      changeMonth: true,
      numberOfMonths: 1,
      onClose: function( selectedDate ) {
        $( "#from" ).datepicker( "option", "maxDate", selectedDate );
      }
    });  
  });  

Start date: <input type="text" id="from" name="from"> 
End date: <input type="text" id="to" name = "to"> 

【问题讨论】:

  • 更新您的问题并添加您拥有的代码。
  • 确认,开始日期应该是今天,结束日期应该是 1 周前(或 7 天前)。

标签: jquery date jquery-ui datepicker jquery-ui-datepicker


【解决方案1】:

您将需要使用setDate 方法。查看更多:https://api.jqueryui.com/datepicker/#method-setDate

设置日期选择器的日期。新日期可以是Date 对象或当前日期格式的字符串(例如,"01/26/2009")、从今天开始的天数(例如,+7)或一串值和句点("y"年,"m" 几个月,"w" 几周,"d" 几天,例如,"+1m +7d"),或 null 以清除选定的日期。

$(function() {
  // Initialize Date Fields
  var from = $("#from").datepicker({
    changeMonth: true,
    numberOfMonths: 1,
    onClose: function(selectedDate) {
      $("#to").datepicker("option", "minDate", selectedDate);
    }
  });
  var to = $("#to").datepicker({
    changeMonth: true,
    numberOfMonths: 1,
    onClose: function(selectedDate) {
      $("#from").datepicker("option", "maxDate", selectedDate);
    }
  });
  // Set Dates
  from.datepicker("setDate", "+0d");
  to.datepicker("setDate", "-7d");
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

Start date: <input type="text" id="from" name="from"> End date: <input type="text" id="to" name="to">

【讨论】:

    猜你喜欢
    • 2010-12-11
    • 1970-01-01
    • 2013-01-12
    • 2011-04-09
    • 1970-01-01
    • 1970-01-01
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多