0

我有一个脚本,可以将日期选择器中的日期分隔为日、月和年。当页面上有一个表单时它工作正常,但当有第二个表单时(可能是由于 id 相同)。如何为我的 id 和 name 添加一个值,使它们成为唯一值?

var now = new Date();
var date = jQuery('.form-date');
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;

date.val(today);

jQuery('form').on('submit', function() {


    var newVal = date.val().split('-'), 
        dateParts = {
            year: parseInt(newVal[0], 10),
            month: parseInt(newVal[1], 10),
            day: parseInt(newVal[2], 10)
        };

    jQuery('.anchor').append(jQuery.map(dateParts, function (index, key) {
        var name = 'date_' + key;

        return jQuery('<input>', {
            type: 'hidden',
            name: name,
            id: name,
            value: dateParts[key]
        });
    }));

});
4

1 回答 1

0

需要声明一个确定当前形式的变量:

(function ($) {
    var now = new Date();
    var date = $('.form-date');
    var day = ("0" + now.getDate()).slice(-2);
    var month = ("0" + (now.getMonth() + 1)).slice(-2);
    var today = now.getFullYear() + "-" + (month) + "-" + (day);

    date.val(today);

    var form = $('form.reservation');

    form.on('submit', function () {
        var currentForm = $(this);
        var newVal = currentForm.find('.form-date').val().split('-'),

            dateParts = {
                year: parseInt(newVal[0], 10),
                month: parseInt(newVal[1], 10),
                day: parseInt(newVal[2], 10)
            };

        currentForm.find('.anchor').append($.map(dateParts, function (index, key) {
            console.log(['date', form.index(currentForm), key].join('_'));
            return $('<input>', {
                type: 'hidden',
                name: ['date', key].join('_'),
                id: ['date', form.index(currentForm), key].join('_'),
                value: dateParts[key]
            });
        }));

    });
})(jQuery); 
于 2014-01-05T09:42:29.993 回答