Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Datepicker - Automatically define altField for all datepickers

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);
});
like image 346
BadHorsie Avatar asked Dec 14 '12 15:12

BadHorsie


2 Answers

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);
like image 128
Frédéric Hamidi Avatar answered Sep 21 '22 15:09

Frédéric Hamidi


Try this:

$('.datepicker input').each(function() {
    var altField = '#_' + $(this).prop('id');
    $(this).datepicker('option', 'altField', altField);
});
like image 20
palaѕн Avatar answered Sep 19 '22 15:09

palaѕн