一个页面上的多个日期选择器,每个都具有动态ID' s

时间:2014-07-29 09:17:33

标签: javascript jquery datepicker

我正在使用表单克隆插件(SheepIt)克隆表单元素,在我的例子中,每个表单都包含一个jQuery日期选择器。

在“普通”表单中,我已将日期选择器附加到课程中,即使我在一个页面上有多个日期选择器,但是因为我不知道表单上可能有多少项目,所以不知道如何添加它到ID。

当我尝试使用SheepIt克隆时,我收到错误:

Uncaught Missing instance data for this datepicker

示例(我已经模拟了三个文本框,但可能有一个或者可能有二十个):

<form>
    <div id="sheepItForm">
        <label for "start_date">Start date:</label>
        <input id="sheepItForm_0_start_date" type="text" name="start_date_0" class="datepicker">
        <label for "start_date">Start date:</label>
        <input id="sheepItForm_1_start_date" type="text" name="start_date_1" class="datepicker">
        <label for "start_date">Start date:</label>
        <input id="sheepItForm_2_start_date" type="text" name="start_date_2" class="datepicker">
        </div>
    </div>
</form>

JS:

$(document).ready(function () {
    $(".datepicker").datepicker({
        firstDay: 1,
        dateFormat: "dd/mm/yy"
    });    
});

SheepIt代码:

<script type="text/javascript">
    $(document).ready(function() {    
        var sheepItForm = $('#sheepItForm').sheepIt({
            separator: '',
            allowRemoveLast: true,
            allowRemoveCurrent: true,
            allowRemoveAll: true,
            allowAdd: true,
            allowAddN: true,
            maxFormsCount: 50,
            minFormsCount: 0,
            iniFormsCount: 1,
            removeLastConfirmation: true,
            removeCurrentConfirmation: true,
            removeAllConfirmation: true,
            removeLastConfirmationMsg: 'Are you sure? This will remove the last added item',
            removeCurrentConfirmationMsg: 'Are you sure? This will remove this item',
            removeAllConfirmationMsg: 'Are you sure? This will remove all items'
        });  
    });
</script>

当数量(以及ID)未知时,如何让datepicker在任何datepicker框中工作?

由于

1 个答案:

答案 0 :(得分:1)

一旦添加了克隆表单(afterAdd),就会有一个回调。你可以在那里初始化datepicker:

    var sheepItForm = $('#sheepItForm').sheepIt({
        separator: '',
        allowRemoveLast: true,
        allowRemoveCurrent: true,
        allowRemoveAll: true,
        allowAdd: true,
        allowAddN: true,
        maxFormsCount: 50,
        minFormsCount: 0,
        iniFormsCount: 1,
        removeLastConfirmation: true,
        removeCurrentConfirmation: true,
        removeAllConfirmation: true,
        removeLastConfirmationMsg: 'Are you sure? This will remove the last added item',
        removeCurrentConfirmationMsg: 'Are you sure? This will remove this item',
        removeAllConfirmationMsg: 'Are you sure? This will remove all items',

        // Callback - initialise datepicker
        afterAdd: function(source, newForm) {
             $(".datepicker").datepicker({
                 firstDay: 1,
                 dateFormat: "dd/mm/yy"
             });
        }
    });