JQuery Datepicker - 没有默认日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3668325/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:52:47  来源:igfitidea点击:

JQuery Datepicker - no default date

jqueryjquery-uidatepicker

提问by user352985

I want to remove the default date in my JQuery Datepicker.

我想删除 JQuery Datepicker 中的默认日期。

I try the following code:

我尝试以下代码:

$(this).datepicker({defaultDate: ''});

But it doesn't seem to work. Today's date is still selected as default.

但它似乎不起作用。仍然选择今天的日期作为默认日期。

回答by Lee Gunn

I got round the problem using a hidden altField:

我使用隐藏的 altField 解决了这个问题:

<div id="DatePicker"></div>
<input type="hidden" value="" name="Date" id="Date" />

and the following script:

以及以下脚本:

<script>
    $(function () {

        $('#DatePicker').datepicker({
            altField: '#Date', // ID of the hidden field
            altFormat: 'dd/mm/yy'
        });

        // Remove the style for the default selected day (today)
        $('.ui-datepicker-current-day').removeClass('ui-datepicker-current-day');

        // Reset the current selected day
        $('#Date').val('');
    });
</script>

Then, I used the hidden #Date field in my validation routines.

然后,我在验证例程中使用了隐藏的 #Date 字段。

回答by J. Polfer

None of the answers at the time of this writing really worked for me, so here was my solution cobbled from a couple of answers (for an inline datepicker).

在撰写本文时,没有一个答案对我真正有用,因此这是我的解决方案(针对内联日期选择器)由几个答案拼凑而成。

    $('.calendar').datepicker("setDate", null); // this unsets the datepicker's internal selected date; it still shows a highlight on today's date that looks like a selected date though
    $('.calendar').find(".ui-datepicker-current-day").removeClass("ui-datepicker-current-day"); // this actually removes the highlight

回答by BruceHill

This is actually an open issue with jQuery UI Datepicker. Here is the ticket for the issue:

这实际上是jQuery UI Datepicker 的一个悬而未决的问题。这是问题的票证:

Ticket 8159

票 8159

At the heart of this issue is the fact that Datepickerincorrectly handles a defaultDatevalue of null. Of the solutions offered here, I like that of j-polferthe best and upvoted it for that reason. The reason this solution works, though, is because there is a patch built into the setDatemethod to clear the selection if nullis passed into the date parameter. But I wanted to find out whythe Datepicker was not responding correctly to the defaultDate:nullin the options, and so I took a look at the source.

这个问题的核心是Datepicker错误地处理了nulldefaultDate值。在这里提供的解决方案中,我最喜欢j-polfer的解决方案,并因此对它了赞成票。但是,此解决方案之所以有效,是因为setDate方法中内置了一个补丁,用于在将null传递到 date 参数时清除选择。但我想找出为什么Datepicker 没有正确响应选项中的defaultDate:null,所以我查看了源代码。

I found that I needed to make three changes to the Datepickersource code to fix this issue. Here are the changes that I made:

我发现我需要对Datepicker源代码进行三处更改才能解决此问题。以下是我所做的更改:

  1. The method _getDefaultDatereturned the current date when defaultDateoption was null or missing (This is the heart of the problem).
  1. defaultDate选项为 null 或缺失时,方法_getDefaultDate返回当前日期(这是问题的核心)。

I changed this method from this...

我从这个改变了这个方法......

    _getDefaultDate: function(inst) {
        return this._restrictMinMax(inst,this._determineDate(inst,this._get(inst, "defaultDate"), new Date()));
    }

to this....

到这....

_getDefaultDate: function(inst) {
    var def = this._get(inst, "defaultDate");
    return def !== null ? this._restrictMinMax(inst, this._determineDate(inst, def , new Date())): null;
},
  1. The method _setDatewas setting the selected day to the current day when null was passed into the date parameter. I changed to lines to correct this:
  1. 方法_setDate将所选日期设置为当 null 传递到 date 参数时的当天。我改为线来纠正这个:

I changed this line...

我改变了这一行...

inst.selectedDay = inst.currentDay = newDate.getDate();

to...

到...

inst.selectedDay = date == null? 0: inst.currentDay = newDate.getDate();

and this line...

而这一行...

this._adjustInstDate(inst);

to...

到...

if (date != null) {
    this._adjustInstDate(inst);
}
  1. Lastly, the method _generateHTMLdid not handle a return value of null from _getDefaultDate.
  1. 最后,方法_generateHTML没有处理来自_getDefaultDate的 null 返回值。

So I changed this line...

所以我改变了这一行...

    (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime()) ?

to...

到...

(defaultDate != null && (defaultDate.getTime() === printDate.getTime() && defaultDate.getTime() === selectedDate.getTime())) ?

That's it. Now the DatepickerdefaultDateoption responds more intuitively to a value of nullbeing passed in or to this option being missing.

就是这样。现在Datepicker defaultDate选项可以更直观地响应传入的null值或缺少此选项。

$('#test').datepicker({ altField: '#alt'});  // No date selected
$('#test').datepicker({ altField: '#alt', defaultDate: null});  // No date selected
$('#test').datepicker({ altField: '#alt', defaultDate: 0});  // Today selected
$('#test').datepicker({ altField: '#alt', defaultDate: +1});  // Tomorrow selected
$('#test').datepicker({ altField: '#alt', defaultDate: -1});  // Yesterday selected

Here is a demo in JSFIDDLE: Datepicker demo with defaultDate null

这是JSFIDDLE 中的一个演示:Datepicker demo with defaultDate null

Please note:These changes have not been exhaustively tested, so there may be other issues arising from the fact that _getDefaultDate method now could return null. So do your own testing first! ;)

请注意:这些更改尚未经过详尽测试,因此 _getDefaultDate 方法现在可能会返回 null 的事实可能会引起其他问题。所以先做你自己的测试!;)

Hope this helps someone! :)

希望这可以帮助某人!:)

回答by Chris Hall

Based on the answers posted here, I managed to make something that worked. For my purposes, I had an always visible calendar. If you require this for a popup calendar, you should be able to use the existing onSelecthandler to perform something similar the first time it's opened.

根据此处发布的答案,我设法做出了一些有用的东西。出于我的目的,我有一个始终可见的日历。如果您需要将其用于弹出式日历,您应该能够使用现有的onSelect处理程序在第一次打开时执行类似的操作。

$("selector").datepicker(/* options */).find(".ui-state-active").removeClass("ui-state-active");

Thankfully, it's really that simple with the latest version of jQuery UI (1.10.2 as of this writing). It doesn't appear to interfere with the correct functioning of the widget. The only caveat is that using the getDategetter results in what would have normally been the default selected date.

值得庆幸的是,使用最新版本的 jQuery UI(撰写本文时为 1.10.2)确实如此简单。它似乎不会干扰小部件的正确运行。唯一需要注意的是,使用getDategetter 会导致通常默认选择的日期。

For the purposes of my code, this is acceptable as my users cannot continue (they don't even have the continue button) until they've clicked on a valid date from the picker. If this isn't the case for you, something like Florian Peschka's answershould get you what you need.

就我的代码而言,这是可以接受的,因为我的用户在单击选择器中的有效日期之前无法继续(他们甚至没有继续按钮)。如果您不是这种情况,像Florian Peschka's answer这样的东西应该可以满足您的需求。

回答by Garis M Suero

To open the datepicker dialog it must be opened in some month of some year. I mean, you want to display this dialog and be blank?...

要打开日期选择器对话框,它必须在某年的某个月份打开。我的意思是,你想显示这个对话框并且是空白的?...

I think if you don't want to pass any default date, the best you can do is get the current date with:

我想如果你不想传递任何默认日期,你能做的最好的事情就是通过以下方式获取当前日期:

$(document).ready(function() {
  $('#datepicker').datepicker();
});

Passing this will fail, because of given defaultDate, not null but blank

传递这将失败,因为给定的 defaultDate,不是 null 而是空白

$(this).datepicker({defaultDate: ''});

This is something that will do what intended in the previous code

这将执行之前代码中的意图

$(this).datepicker({defaultDate: null});

but it's behavior is the same as the first code block in this answer.

但它的行为与此答案中的第一个代码块相同。

回答by Remy Mellet

I have the same probleme using inlinedatepicker. The plugin add on today's cell/td the class .ui-datepicker-current-day and .ui-state-active. My solution is to use a custom class such as .ui-datepicker-selected-day and implements beforeShowDay to handle youself the display of the selected day. Something like that:

我使用内联日期选择器也有同样的问题。该插件在今天的单元格/td 上添加了 .ui-datepicker-current-day 和 .ui-state-active 类。我的解决方案是使用自定义类,例如 .ui-datepicker-selected-day 并实现 beforeShowDay 来处理您自己所选日期的显示。类似的东西:

$("datepicker").datepicker({
  beforeShowDay: function(date) {
  var dateIso = $.datepicker.formatDate("yy-mm-dd", date);
  var dateSelected = $("input").val();
  var classDate = "";
  if(dateSelected === dateIso){
    return [false,"ui-datepicker-selected-day"];
  }else{
    return [true];
  }
}

Sample of css to put in "highlight" the cell:

用于“突出显示”单元格的 css 示例:

.ui-widget-content .ui-datepicker-selected-day .ui-state-active{
  background-color: red;
}
+ disable some css from the plugin

回答by Ed DeGagne

I know this is an old question, and I found it because I had the same requirement; do not display a date in the input (textbox), make the user select a date from the datepicker.

我知道这是一个老问题,我找到它是因为我有同样的要求;不要在输入(文本框)中显示日期,让用户从日期选择器中选择一个日期。

The Markup (MVC)

标记 (MVC)

<div class="leftContent">
     @Html.TextBox("DateShipOn", Nothing, New With {.class = "DateShipOn", .readonly = "readonly"})
</div>

HTML Output:

HTML 输出:

<div class="leftContent">
    <input id="DateShipOn" class="DateShipOn hasDatepicker" type="text" value="" readonly="readonly" name="DateShipOn">
</div>

Script (in document ready):

脚本(在文档中):

$('.DateShipOn').datepicker({
    constrainInput: true,
    display: true,
    border: true,
    background: true,
    maxDate: "+1m",
    minDate: new Date('@minDate')
});

$('.DateShipOn').datepicker("setDate", new Date());

The effect of the above code is that the input box has the value of the 'minDate' variable in it on display AND when clicking on the input, the datepicker drops down and the 'minDate' is selected by default.

上面代码的效果是输入框在显示时具有“minDate”变量的值,并且当单击输入时,日期选择器下拉并且默认选择“minDate”。

Note: We do not allow manual input, this is the reason for the 'readonly' attribute.

注意:我们不允许手动输入,这是 'readonly' 属性的原因。

Resolution:

解析度:

All I had to do, in my case, was comment/remove the line:

就我而言,我所要做的就是评论/删除该行:

$('.DateShipOn').datepicker("setDate", new Date());

The Result:

结果:

The effect is that on display;

效果就是展示出来的;

  • There is no default date value in the input (textbox)
  • The user cannot type in the input (textbox)
  • The date picker drops down with no default date selected
  • The minDate prevents dates prior the minDate value from being selected
  • The maxDate prevents dates after the maxDate value from being selected
  • 输入(文本框)中没有默认日期值
  • 用户无法输入输入(文本框)
  • 日期选择器下拉,未选择默认日期
  • minDate 防止选择 minDate 值之前的日期
  • maxDate 阻止选择 maxDate 值之后的日期

Note: For my requirement the '+1m' for maxDate limits the date selection to only the 30 days from the minDate value.

注意:对于我的要求,maxDate 的“+1m”将日期选择限制为距 minDate 值仅 30 天。

Hope this helps someone out.

希望这可以帮助某人。

回答by Niraj

I used $('.datefield').val('')to show blank instead of showing default date.

我曾经$('.datefield').val('')显示空白而不是显示默认日期。

回答by billmccord

My solution involves overriding jQuery's append so that we can remove the elements each time the HTML is regenerated and appended to the div. This fixes a flashing of the default date when switching months and it also clears the hover.

我的解决方案涉及覆盖 jQuery 的 append,以便我们可以在每次重新生成 HTML 并将其附加到 div 时删除元素。这修复了切换月份时默认日期的闪烁问题,并且还清除了悬停。

(function($) {
    var origAppend = $.fn.append;

    $.fn.append = function () {
        return origAppend.apply(this, arguments).trigger("append");
    };
})(jQuery);

var datePickerDiv = $("#date-picker");
datePickerDiv.bind("append", function() {
  $(this).find(".ui-datepicker-days-cell-over").removeClass("ui-datepicker-days-cell-over");
  $(this).find(".ui-datepicker-today a ").removeClass("ui-state-highlight ui-state-active ui-state-hover");
});

datePickerDiv.datepicker();

回答by Fernando Candido

Works for me:

对我有用:

$(document).ready(function() {
    $("#datepicker .ui-state-active").removeClass("ui-state-active");
    $("#datepicker .ui-state-highlight").removeClass("ui-state-highlight");
    $("#datepicker .ui-datepicker-today").removeClass("ui-datepicker-today");
});