All my datepickers have an automatically-generated hidden field which has the same ID as the datepicker input, but with an underscore prepended.
<div class="datepicker">
<input id="MyField1" type="text" value="" />
<input id="_MyField1" type="hidden" value="" />
</div>
<div class="datepicker">
<input id="MyField2" type="text" value="" />
<input id="_MyField2" type="hidden" value="" />
</div>
And then any field which has class datepicker
gets made into a datepicker.
$('.datepicker input').datepicker({
altFormat: 'yy-mm-dd',
changeMonth: true,
constrainInput: true,
dateFormat: 'dd/mm/y',
minDate: '+0d',
numberOfMonths: 2
});
But how can I also automatically get it to set the altField option for each one?
This doesn't work. I also tried doing the assignment in the original options but that doesn't work either.
$('.datepicker input').each(function() {
var altField = '_' + $(this).prop('id');
$(this).datepicker('option', 'altField', altField);
});
The altField option takes a selector, a jQuery object or an element, not an id
attribute.
Try specifying an id selector:
$(this).datepicker("option", "altField", "#_" + $(this).prop("id"));
Or alternatively, saving a call to $()
and a call to prop()
:
$(this).datepicker("option", "altField", "#_" + this.id);
Try this:
$('.datepicker input').each(function() {
var altField = '#_' + $(this).prop('id');
$(this).datepicker('option', 'altField', altField);
});
jQuery UI Datapicker 1.9, Using altField, altFormat options and overriding internal method
Clone field to store actual value in database format "yy-mm-dd",
and use main field to display formatted value ("dd-mm-yy" in this sample):
$(function() {
var _connectDatepicker = $.datepicker._connectDatepicker;
$.datepicker._connectDatepicker = function(target, inst) {
var $target = $(target);
var $altField = $target.clone(false).appendTo($target.parent()).hide();
inst.settings.altField = $altField;
inst.settings.dateFormat = inst.settings.altFormat = "yy-mm-dd";
_connectDatepicker.call(this, target, inst);
$target.removeAttr("name").datepicker( "option", "dateFormat", "dd-mm-yy");
};
});