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

问题描述 投票:0回答:1

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

$(".datepicker").datepicker().keydown(function (event) {   

    if(event.which === $.ui.keyCode.ENTER)
    {
        event.preventDefault();     
        console.log("enter key pressed " + $(this).val());        
        return false;
    }
});

有什么建议来解决这个问题吗?

jquery datepicker
1个回答
0
投票

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

有点“呵呵”的时刻。基本上,您要做的是,当datePicker小部件关闭时,通过单击日期或用户在字段中键入内容来确定是否选择了日期。所以这里有一些东西可以告诉你。我已经从here中获取了一些内容,就确定触发datepicker的close事件的位置而言,但是根据我的理解,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">
© www.soinside.com 2019 - 2024. All rights reserved.