我有一个脚本可以将日期与日期选择器分为日,月和年。当页面上有一个表单时它可以正常工作,但是当有第二个表单时却没有(大概是由于id是相同的)。如何为我的ID和名称添加值,以便它们是唯一值?
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]
});
}));
});
答案 0 :(得分: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);