jquerydatepickerlivequery

Dynamically generating a jQuery Datepicker with altFields


I'm dynamically generating datepicker's by simply appending the field HTML to a div:

<input type="text" value="" readonly="readonly" name="tier[2][publication_date]" id="publication_date_2" size="10" maxlength="10" tabindex="6" class="publication_date hasDatepicker">
<input type="hidden" name="tier[2][publication_date_db]" id="publication_date_db_2" value="">

Due to the way we store dates, we have a separate field (altfield) for the datepicker which stores our database formatted date selected by the user.

To handle selection of the multiple date pickers I assign a class and use livequery in order to detect onClicks after the page has loaded:

$(".publication_date").livequery(function() {
                $(this).datepicker({
                    dateFormat: "dd M yy",
                    changeYear: true,
                    changeMonth: true,
                    onSelect: function(dateText, inst) {
                        console.log(inst);
                    }
                });
            });

I have a problem in that, how does the datepicker know which altfield to populate? On a single datepicker, one would normally include:

altField: '#start_date_datepicker_altfield', 
altFormat: 'yy-mm-dd',

for the population to occur.


Solution

  • I know the documentation says it takes a selector, but it can also take a jQuery object, so just use $(this).next() to get the hidden field, like this:

    $(".publication_date").livequery(function() {
       $(this).datepicker({
          altField: $(this).next(), 
          altFormat: 'yy-mm-dd',
          dateFormat: "dd M yy",
          changeYear: true,
          changeMonth: true,
          onSelect: function(dateText, inst) {
            console.log(inst);
          }
       });
    });
    

    Since most of the plugins boil down to $(input) that input can be a selector or a jQuery object or a DOM element and it'll still work just fine :)