質問

There is a form with a 'from' and 'until' date, with each a day, month and year box. I want to fill the datePicker with each of these d-m-y values of the selected date ('from' or 'until'). This is what the script looks like:

$('.year').datepicker({
    inline: true,
    showOtherMonths: true,
    showOn: 'button',
    buttonText: '',
    defaultDate: new Date(
        parseInt($('input[name="ydate'+$(this).attr('name').replace(/.date/, '')+'"]').val())
        ,parseInt($('input[name="mdate'+$(this).attr('name').replace(/.date/, '')+'"]').val())-1
        , parseInt($('input[name="ddate'+$(this).attr('name').replace(/.date/, '')+'"]').val())
    ),
    changeYear: true,
    onClose: function(dateText,picker) {
        var prefix = $(this).attr('name').replace(/.date/, '');

        $('input[name="ddate'+prefix+'"]').val( dateText.split(/\//)[1] );
        $('input[name="mdate'+prefix+'"]').val( dateText.split(/\//)[0] );
        $('input[name="ydate'+prefix+'"]').val( dateText.split(/\//)[2] );

    }
});

The onClose event fills the d-m-y inputfields just fine, but the defaultDate wont work like this. Any suggestions?

役に立ちましたか?

解決

Since the execution context is not changed, this still refers to the method's context in which the datepicker is initialized.

So the solution could be is to iterate through the set of .year elements using .each(), now inside the each handler this will refer to the current .year element.

$('.year').each(function () {
    var nm = $(this).attr('name').replace(/.date/, '');
    $(this).datepicker({
        inline: true,
        showOtherMonths: true,
        showOn: 'button',
        buttonText: '',
        defaultDate: new Date(
        parseInt($('input[name="ydate' + nm + '"]').val()), parseInt($('input[name="mdate' + nm + '"]').val()) - 1, parseInt($('input[name="ddate' + nm + '"]').val())),
        changeYear: true,
        onClose: function (dateText, picker) {
            var prefix = $(this).attr('name').replace(/.date/, '');

            $('input[name="ddate' + prefix + '"]').val(dateText.split(/\//)[1]);
            $('input[name="mdate' + prefix + '"]').val(dateText.split(/\//)[0]);
            $('input[name="ydate' + prefix + '"]').val(dateText.split(/\//)[2]);

        }
    });
})
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top