开发者

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 m开发者_运维问答ultiple 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.


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 :)


I haven't used livequery, but from the looks of it, you can get the id of the matched element from this.id. In your example HTML, that will be "publication_date_2", from which it's relatively easy to create the necessary ID for the altfield "publication_date_db_2" (you can make it even easier by changing your strategy of naming the field).

So perhaps:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜