jQuery datepicker altFormat不显示 [英] jQuery datepicker altFormat not displayed
问题描述
我有一个jQuery datepicker,它根据卖方的语言偏好进行了本地化.每个datepicker定制都有不同的日期格式,但是我希望在提交表单时输入特定的格式进行解析.我正在尝试在日期选择器上使用altFormat将其设置为"mm/dd/yy",但我不希望该日期以显示给用户的格式显示.有没有办法做到这一点. IE.创建JavaScript日期对象时,有没有一种方法可以使日期选择器的日期格式不同,以求出相同的日期?
I have a jQuery datepicker that is localized based on the language preferences of the seller. Each datepicker customization has a different date format but I want the input when the form is submitted to be in a specific format for parsing. I am trying to use altFormat on the date picker to set this to 'mm/dd/yy' but I do not want the date in the format shown to the user. Is there a way to do this. I.e. is there a way to have different date formats from a datepicker to evaluate to the same date when creating javascript date objects?
推荐答案
为什么不想使用 altField 吗?
在一个简单的示例中,您可以按所需格式mm/dd/yy
存储和访问日期,同时以其"所需格式向用户显示日期.参见我的 jsfiddle 在按钮上,单击显示的格式更改,但altField中的格式没有更改.
In a simple example here you can store and access the date in your desired format mm/dd/yy
while showing it to the user in "his" desired format. See my jsfiddle On button click the shown format changes but the format in the altField doesn't.
<input type="text" id="datepicker">
<input type="button" id="changeFormat" value="Change!">
<!-- this would be a hidden input -->
<input type="text" id="altFormat">
$(document).ready(function () {
$('#datepicker').datepicker({
dateFormat: "dd.mm.yy",
altFormat: "dd/mm/yy",
altField: '#altFormat'
});
$('#changeFormat').click(function () {
//changes the dateformat the user sees
$('#datepicker').datepicker('option', 'dateFormat', 'dd-mm-yy');
console.log($('#datepicker').datepicker('option', 'altFormat'));
});
});
((在第一个示例中误用了dd/mm/yy而不是mm/dd/yy)
((accidentally used dd/mm/yy instead of mm/dd/yy in the 1st example))
编辑
此 工作示例 将日期以mm/dd/yy
格式存储在您可以轻松访问的data-altformat
属性
This working example stores the date in mm/dd/yy
format in the data-altformat
attribute which you can easily access with
$('#datepicker').data('altformat'); //outputs e.g. 05/31/2013
onSelect我这样做是将currentDate的值存储在属性中
onSelect I store the value of the currentDate in the attribute by doing
onSelect: function () {
//gets your desired format
var altFormat = $(this).datepicker('option', 'altFormat');
//get current date in user format
var currentDate = $(this).datepicker('getDate');
//format from user format to desired format
var formatedDate = $.datepicker.formatDate(altFormat, currentDate);
//set data-* attribute to formatedDate
$('#datepicker').data('altformat', formatedDate);
$('#altFormat').val(formatedDate);
}
此方法的优点是您不再需要隐藏的输入. 希望对您有帮助.
The advantage with this method is that you don't need a hidden input anymore. I hope this may help you.
EDIT2
只是注意到您不需要new Date()
和.datepicker('getDate')
Just noticed that you don't need new Date()
with .datepicker('getDate')
这篇关于jQuery datepicker altFormat不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!