当空文本框上按下回车键时,JQuery datepicker默认为今天的日期

时间:2017-12-26 16:03:55

标签: jquery datepicker

每当在datepicker文本框中按下回车键时,就会填充今天的日期。 可以在Jquery Datepicker site上看到此行为。此外,如果我键入一个随机文本,如34123123123并按Enter键,它将解析为当前日期。 我想避免这种行为。我尝试使用下面的代码处理它,但没有运气..

{{1}}

有任何解决此问题的建议吗?

1 个答案:

答案 0 :(得分:0)

虽然在早期的一个版本中,我天真地说“使用你给的工具”,你可能需要扩展它们。

有点“呵呵”的时刻。基本上,您要做的是,当datePicker小部件关闭时,通过单击日期或用户在字段中键入内容来确定是否选择了日期。所以这里有一些东西可以告诉你。我已经从 here 中获取了一些内容,以确定触发日期选择器的关闭事件的位置,但是onClose函数本身必须重写以适合您的用例,目前为止我可以理解。

$(function() {
  var datePicker = $('#datepicker');
  datePicker.data('closedOn', 'document').datepicker({
    showButtonPanel: true,
    onClose: function(date, options) {
      //  your logic goes here ...
      var dateEl = $(this);
      // so we either clicked out of the date select or we hit enter
      //   in the input. In this case we should use the data-oldValue
      //   we've been building in the keyup/blur trigger for the input.
      //
      if (dateEl.data('closedOn') == 'document') {
        // if the user has entered MANUALLY a valid format date...
        if(Date.parse(dateEl.data("oldValue")) ) {
          console.log("Manually entered a valid date!");
          dateEl.val(dateEl.data("oldValue"));
        } else {
          console.log("Not a valid date format...")
          dateEl.val("");
        }
      } else {
        // Here, the user has clicked on a date in the calendar widget.
        //  If there were some sort of desired processing, that could
        //  happen here.
      }
    }
  }).on("keyup", function(){
    $(this).data("oldValue", $(this).val() );
})
  .datepicker('widget').on('mousedown', function(event) {
  /***
   * Listener to detect if the user
   *  has closed the calendar by clicking
   *  on a given date, or by any other means.
   *  This will tell us if the date was changed
   *  by the date picker, or manually.
   ***/
    var $this = $(this);
    var target = $(event.target);
    // If the button panel is enabled, and the user has
    //  clicked there...
    if (target.hasClass('ui-datepicker-close')) {
      datePicker.data('closedOn', 'byButtonPanel');
    };
    // Or if the user has clicked on a given date in the
    //  calendar widget...
    if (typeof target.parent().data('month') != 'undefined') {
      datePicker.data('closedOn', 'byDateSelect');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet"/>

<input type="text" id="datepicker">