javascript jQuery datepicker 没有正确更新值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27188754/
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
jQuery datepicker does not update value properly
提问by SemperMemento
On the website I'm currently working I have a form to add a event. This event needs a date which the user selects using a jQuery datepicker. A date can only have one event. So I want to check the date the user insert in the datepicker. I tried doing this by getting the value after the user has selected the date. The problem is however, the datepickers doesn't update his value right away.
在我目前工作的网站上,我有一个添加事件的表单。此事件需要用户使用 jQuery 日期选择器选择的日期。一个日期只能有一个事件。所以我想检查用户在日期选择器中插入的日期。我尝试通过在用户选择日期后获取值来做到这一点。然而,问题是日期选择器不会立即更新他的值。
I made a JSFiddle to show the problem. When you pick a date the span updates and shows the value of the datepicker. But as you can see the first time it is blank, and the second time it shows the previous selected date. So the datepickers does not update is value right away. How can I fix this?
我做了一个 JSFiddle 来显示问题。当您选择一个日期时,跨度会更新并显示日期选择器的值。但是正如您所看到的,第一次它是空白的,第二次它显示了上一个选定的日期。所以日期选择器不会立即更新值。我怎样才能解决这个问题?
I looked trough other similar questions here on stackoverflow but their solutions didn't work for me.
我在stackoverflow上查看了其他类似的问题,但他们的解决方案对我不起作用。
JSFiddle:http://jsfiddle.net/kmsfpgdk/
JSFiddle:http : //jsfiddle.net/kmsfpgdk/
HTML:
HTML:
<input type="text" id="datepicker" name="date" />
<span id="data"></span>
JS:
JS:
$('#datepicker').datepicker();
$('#datepicker').blur(function () {
var val = $(this).val();
$('#data').text(val);
});
回答by Jai
Its better to use built in method onSelect:fn
to use:
最好使用内置方法onSelect:fn
来使用:
$('#datepicker').datepicker({
onSelect: function () {
$('#data').text(this.value);
}
});
Fiddle
小提琴
As per documentation:
根据文档:
Called when the datepicker is selected. The function receives the selected date as text and the datepicker instance as parameters. thisrefers to the associated input field.
在选择日期选择器时调用。该函数接收所选日期作为文本和日期选择器实例作为参数。这是指相关的输入字段。
回答by Rahul Desai
change
event happens before blur
event.
change
事件发生在blur
事件之前。
Use .change()
instead of .blur()
使用.change()
代替.blur()
$('#datepicker').change(function() {
var val = $(this).val();
$('#data').text(val);
});