jQuery如何将今天的日期从输入分为月份,日期,年份,而不使用datepicker

我有一个datepicker输入,填充页面加载的今天的日期。 使用datepicker时,日期将分为月,日和年,并放入三个隐藏字段,这些字段将使用发布数据发送到服务器。 当用户决定今天的日期没有问题并且不使用日期选择器时,就会出现问题; 如何将日期片段分成这三个隐藏的字段?

我尝试将今天的日期分成几部分并将其添加到这些字段中,但我尝试将其添加到jQuery或使用普通JavaScript的每一种方式都打破了整个过程。 这是我想要构建的工作代码:

jQuery的

$(function() { //set your date picker $("#CI").datepicker({ dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true, showOn: "both", buttonImage: "css/images/calendar-green.gif", buttonImageOnly: true, buttonImageText: "Calendar", beforeShow: function(dateText, instance) { $("#CI").datepicker('setDate', new Date()); }, onSelect: function(dateText, instance) { var pieces = dateText.split("/"); $("#CID").val(pieces[0]); $("#CIM").val(pieces[1]); $("#CIY").val(pieces[2]); } }) //get the current date var todaysDate = new Date(); //format the date in the right format (add 1 to month because JavaScript counts from 0) formatDate = (todaysDate.getMonth() + 1) + '/' + todaysDate.getDate() + '/' + todaysDate.getFullYear(); //set the input value $('#CI').val(formatDate); }); 

HTML

     

onSelect()function拆分为单独的函数,可以将它们调用两次。

具有执行这两个任务的相同function允许您处理对function或HTML结构的任何更改。

所以…

 $(function() { function populateHidden(dateText){ var pieces = dateText.split("/"); $("#CID").val(pieces[0]); $("#CIM").val(pieces[1]); $("#CIY").val(pieces[2]); } //set your date picker $("#CI").datepicker({ dateFormat: 'mm/dd/yy', changeMonth: true, changeYear: true, showOn: "both", buttonImage: "css/images/calendar-green.gif", buttonImageOnly: true, buttonImageText: "Calendar", beforeShow: function(dateText, instance) { $("#CI").datepicker('setDate', new Date()); }, onSelect: populateHidden }) //get the current date var todaysDate = new Date(); //format the date in the right format (add 1 to month because JavaScript counts from 0) formatDate = (todaysDate.getMonth() + 1) + '/' + todaysDate.getDate() + '/' + todaysDate.getFullYear(); //set the input value $('#CI').val(formatDate); populateHidden(formatDate); }); 

使用以下代码:

  //get the current date var todaysDate = new Date(); //format the date in the right format (add 1 to month because JavaScript counts from 0) var month = todaysDate.getMonth() + 1 ; var date = todaysDate.getDate(); var year =todaysDate.getFullYear() ; formatDate = month + '/' + date+ '/' + year; //set the input value $('#CI').val(formatDate); $("#CID").val(date); $("#CIM").val(month); $("#CIY").val(year);