如何在jquery ui DatePicker中拒绝onSelect中的选定日期

时间:2016-09-29 23:42:54

标签: jquery-ui datepicker

我有一个网络表单,我要求用户提供几个日期。通常,但并非总是,重复的日期将是人为错误。因此,在onSelect功能中,我检查是否已输入日期,并要求用户确认重复日期是否是故意的。如果用户说“否”,如何从选择器中清除日期值?

// datesList initialized in outer scope

onSelect: function (thedate, picker) {


     if ($.inArray(new Date(thedate).valueOf(), datesList) == -1) {
        //store chosen dates in datesList if we haven't seen it before
        datesList.push(new Date(thedate).valueOf())

       } else {
            // ask the user if it was intentional
            //if unintentional, reject the choice and clear the picker


       }

    }

1 个答案:

答案 0 :(得分:2)

不确定您是否可以使用给定选项执行此操作,但您可以覆盖 _selectDate 并添加条件。像这样:

$.datepicker._selectDate = function(id, dateStr) {
  var target = $(id);
  var inst = this._getInst(target[0]);
  dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
  if (inst.input)
    inst.input.val(dateStr);
  this._updateAlternate(inst);
  var onSelect = this._get(inst, 'onSelect');
  if (onSelect){
    // you get the value of onSelect
    var shouldHide = onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
    } else if (inst.input && shouldHide){
    inst.input.trigger('change'); // fire the change event
      }
  if (inst.inline)
    this._updateDatepicker(inst);
    // If onSelect return false, you don't hide the datepicker
  else if (shouldHide) {

    this._hideDatepicker();
    this._lastInput = inst.input[0];
    if (typeof(inst.input[0]) != 'object')
      inst.input.focus(); // restore focus
    this._lastInput = null;
  }
}


$('input').datepicker({
  onSelect: function(e, ui) {
    if (confirm('OK?')) {

      return true;
    } else {
      this.value = "";
      return false;
    }
  }

});
<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.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"></link>
<input type=text></input>