How to populate two texboxes using a javascript calendar control? - javascript

I need to populate the date time values in two textboxes at a same instant using a calendar control. Like on client side click of calendar control, the selected date in that control should get poulate on the corresponding textbox defined for say start date. There is an another textbox say enddate which also have to be populated with the same value on client click. Is there any third party javascript file to handle this scenario to populate two textboxes. Pls help me out on this?

Add this in ur page
<script language="JavaScript" src="calendardel.js"></script>
calendardel.js file code
// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR = 30;
// is time input control required by default
var BUL_TIMECOMPONENT = false;
// are year scrolling buttons required by default
var BUL_YEARSCROLL = true;
var calendars = [];
var RE_NUM = /^\-?\d+$/;
function calendardel(obj_target) {
// assing methods
this.gen_date = cal_gen_date1;
this.gen_time = cal_gen_time1;
this.gen_tsmp = cal_gen_tsmp1;
this.prs_date = cal_prs_date1;
this.prs_time = cal_prs_time1;
this.prs_tsmp = cal_prs_tsmp1;
this.popupdel = cal_popup1del;
// validate input parameters
if (!obj_target)
return cal_error("Error calling the calendar: no target control specified");
if (obj_target.value == null)
return cal_error("Error calling the calendar: parameter specified is not valid target control");
this.target = obj_target;
this.time_comp = BUL_TIMECOMPONENT;
this.year_scroll = BUL_YEARSCROLL;
// register in global collections
this.id = calendars.length;
calendars[this.id] = this;
}
function cal_popup1del (str_datetime) {
this.dt_current = this.prs_tsmp(str_datetime ? str_datetime : this.target.value);
if (!this.dt_current) return;
var obj_calwindow = window.open(
'calendardel.html?datetime=' + this.dt_current.valueOf()+ '&id=' + this.id,
'Calendar', 'width=200,height='+(this.time_comp ? 265 : 230)+
',status=no,resizable=no,top=200,left=200,dependent=yes,alwaysRaised=yes'
);
obj_calwindow.opener = window;
obj_calwindow.focus();
}
// timestamp generating function
function cal_gen_tsmp1 (dt_datetime) {
return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}
// date generating function
function cal_gen_date1 (dt_datetime) {
var ARR_MONTHS1 = ["Jan", "Feb", "Mar", "Apr", "May", "Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var month=ARR_MONTHS1[eval(dt_datetime.getMonth())]; //previous code in place of month=(dt_datetime.getMonth() < 9 ? '0' : '') +dt_datetime.getMonth() + 1
// alert(month);
return (
(dt_datetime.getDate() < 10 ? '0' : '') + dt_datetime.getDate() + "-"
+ (month) + "-"
+ dt_datetime.getFullYear()
);
}
// time generating function
function cal_gen_time1 (dt_datetime) {
return (
(dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
+ (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) + ":"
+ (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
);
}
// timestamp parsing function
function cal_prs_tsmp1 (str_datetime) {
// if no parameter specified return current timestamp
if (!str_datetime)
return (new Date());
// if positive integer treat as milliseconds from epoch
if (RE_NUM.exec(str_datetime))
return new Date(str_datetime);
var arr_date=str_datetime.split('-');
if(arr_date.length!=3)
{
str_datetime="";
this.target.value="";
return new Date(str_datetime);
}
// else treat as date in string format
//=====================================================================\\
//=====================================================================\\
var arr_datetime = str_datetime.split(' ');
return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0]));
}
// date parsing function
function cal_prs_date1del (str_dateField) {
//=====================================================================\\
//=====================================================================\\
str_date=str_dateField.value;
//alert(str_date);
//if not str_date field is a value======\\
if(!str_date)
str_date = str_dateField;
//=====================================================================\\
//=====================================================================\\
if(str_dateField.value=="")
return true;
var validmonth=false;
var Month=0;
var ARR_MONTH = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN","JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
var arr_date = str_date.split('-');
if(arr_date.length >3)
{
str_dateField.value = '';
str_dateField.focus();
alert("Invalid date format: '" + str_date + "'.\nFormat accepted is DD-MON-YYYY.");
return false;
}
//=====================================================================\\
//=====================================================================\\
//===========if date format is dd-mon-yyyy================================
if(arr_date.length == 3)
{
//=====================================================================\\
var mon=arr_date[1];
mon=mon.toUpperCase(mon);
for(i=0;i<ARR_MONTH.length;i++)
{
if(mon==ARR_MONTH[i])
{
Month=i+1;
validmonth=true;
break;
}
}
//=====================================================================\\
if (arr_date.length < 3)
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is DD-MON-YYYY.");
}
if (!arr_date[0])
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
}
if (!RE_NUM.exec(arr_date[0]))
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
}
if (!arr_date[1])
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
}
if (validmonth==false)
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed values are month abbr..");
}
if (!arr_date[2])
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
}
if (!RE_NUM.exec(arr_date[2]))
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");
}
var dt_date = new Date();
dt_date.setDate(1);
if (Month < 1 || Month > 12) return cal_error ("Invalid month value: '" + arr_date[1] + "'.\nAllowed range is 01-12.");
dt_date.setMonth(Month-1);
if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
dt_date.setFullYear(arr_date[2]);
var dt_numdays = new Date(arr_date[2], Month, 0);
dt_date.setDate(arr_date[0]);
if (dt_date.getMonth() != (Month-1)) return cal_error ("Invalid day of month value: '" + arr_date[0] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");
return (dt_date)
}
else //====date format is mon-yyyy or hh-yyyy or qq-yyyy or yyyy
{
if(arr_date.length == 1)
{
//check for year value only
if (!RE_NUM.exec(arr_date[0]))
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid year value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
}
}
else
{
if(arr_date[0].length == 3) //========check for month validity
{
//=====================================================================\\
var mon=arr_date[0];
mon=mon.toUpperCase(mon);
for(i=0;i<ARR_MONTH.length;i++)
{
if(mon==ARR_MONTH[i])
{
Month=i+1;
validmonth=true;
break;
}
}
//=====================================================================\\
if (validmonth==false)
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid month value: '" + arr_date[0] + "'.\nAllowed values are month abbr..");
}
//=====================================================================\\
}
else
{
//=========check for hh/qq
if(arr_date[0]== 'H2' || arr_date[0]== 'H1' || arr_date[0]== 'Q1' || arr_date[0]== 'Q2' || arr_date[0]== 'Q3' || arr_date[0]== 'Q4')
{
}
else
{
str_dateField.value = '';
str_dateField.focus();
return cal_error ("Invalid date format: '" + str_date + "'.\nFormat accepted is DD-MON-YYYY.");
}
}
//=====================================================================\\
//=====================================================================\\
}
}
}
// time parsing function
function cal_prs_time1 (str_time, dt_date) {
if (!dt_date) return null;
var arr_time = String(str_time ? str_time : '').split(':');
if (!arr_time[0]) dt_date.setHours(0);
else if (RE_NUM.exec(arr_time[0]))
if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");
if (!arr_time[1]) dt_date.setMinutes(0);
else if (RE_NUM.exec(arr_time[1]))
if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");
if (!arr_time[2]) dt_date.setSeconds(0);
else if (RE_NUM.exec(arr_time[2]))
if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");
dt_date.setMilliseconds(0);
return dt_date;
}
function cal_error (str_message) {
alert (str_message);
return null;
}
then HTML code
<input name="dat" type="text" id="dat" size="11" maxlength="11" tabindex="1" value="">
<img src="img/cal.gif" alt="Click here to pick up the date" width="16" height="16" border="0" align="absmiddle">
and then add that script in script part
var cal1= new calendardel(document.forms['formname'].elements['dat']);
cal1.year_scroll = true;
cal1.time_comp = false;

You can use the OnChange event of the first input?
<script type="text/javascript">
function Text1OnChange() {
document.getElementById("Text2").value = document.getElementById("Text1").value;
}
</script>
<input id="Text1" type="text" onchange="Text1OnChange()"/>
<input id="Text2" type="text" />
Edit:
For asp TextBox, do not know if there is a better way, but it works.
<script type="text/javascript">
function <%= TextBox1.ClientID %>OnChange() {
document.getElementById("<%= TextBox2.ClientID %>").value = document.getElementById("<%= TextBox1.ClientID %>").value;
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
I could not put the js function name directly in the declaration of the textbox, it should change according to the id of the textbox, then put it in codebehind ...
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Attributes.Add("onchange", TextBox1.ClientID + "OnChange();");
}
other way:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<script type="text/javascript">
document.getElementById("<%= TextBox1.ClientID %>").onchange = function () {
document.getElementById("<%= TextBox2.ClientID %>").value = document.getElementById("<%= TextBox1.ClientID %>").value;
}
</script>

Related

Ignore Sundays from jQuery date range picker

I'm using the following jQuery date range picker library : http://longbill.github.io/jquery-date-range-picker/
I would like to remove / hide all Sundays from all date range pickers while keeping a normal behavior on the date range pickers.
I tried to do something with beforeShowDay option :
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = '';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
but it only "disables" all Sundays whereas I want to remove / hide them:
Here's the fiddle I'm working on : https://jsfiddle.net/maximelafarie/dnbd01do/11/
EDIT:
Updated fiddle with #Swanand code: https://jsfiddle.net/maximelafarie/dnbd01do/18/
You could do it with just a little CSS but it does leave a gap:
.week-name th:nth-child(7),
.month1 tbody tr td:nth-child(7) {
display: none;
}
Hope this helps a little.
You need do changes in two functions in your daterangepicker.js file:
createMonthHTML()
function createMonthHTML(d) { var days = [];
d.setDate(1);
var lastMonth = new Date(d.getTime() - 86400000);
var now = new Date();
var dayOfWeek = d.getDay();
if ((dayOfWeek === 0) && (opt.startOfWeek === 'monday')) {
// add one week
dayOfWeek = 7;
}
var today, valid;
if (dayOfWeek > 0) {
for (var i = dayOfWeek; i > 0; i--) {
var day = new Date(d.getTime() - 86400000 * i);
valid = isValidTime(day.getTime());
if (opt.startDate && compare_day(day, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(day, opt.endDate) > 0) valid = false;
days.push({
date: day,
type: 'lastMonth',
day: day.getDate(),
time: day.getTime(),
valid: valid
});
}
}
var toMonth = d.getMonth();
for (var i = 0; i < 40; i++) {
today = moment(d).add(i, 'days').toDate();
valid = isValidTime(today.getTime());
if (opt.startDate && compare_day(today, opt.startDate) < 0) valid = false;
if (opt.endDate && compare_day(today, opt.endDate) > 0) valid = false;
days.push({
date: today,
type: today.getMonth() == toMonth ? 'toMonth' : 'nextMonth',
day: today.getDate(),
time: today.getTime(),
valid: valid
});
}
var html = [];
for (var week = 0; week < 6; week++) {
if (days[week * 7].type == 'nextMonth') break;
html.push('<tr>');
for (var day = 0; day < 7; day++) {
var _day = (opt.startOfWeek == 'monday') ? day + 1 : day;
today = days[week * 7 + _day];
var highlightToday = moment(today.time).format('L') == moment(now).format('L');
today.extraClass = '';
today.tooltip = '';
if (today.valid && opt.beforeShowDay && typeof opt.beforeShowDay == 'function') {
var _r = opt.beforeShowDay(moment(today.time).toDate());
today.valid = _r[0];
today.extraClass = _r[1] || '';
today.tooltip = _r[2] || '';
if (today.tooltip !== '') today.extraClass += ' has-tooltip ';
}
var todayDivAttr = {
time: today.time,
'data-tooltip': today.tooltip,
'class': 'day ' + today.type + ' ' + today.extraClass + ' ' + (today.valid ? 'valid' : 'invalid') + ' ' + (highlightToday ? 'real-today' : '')
};
if (day === 0 && opt.showWeekNumbers) {
html.push('<td><div class="week-number" data-start-time="' + today.time + '">' + opt.getWeekNumber(today.date) + '</div></td>');
}
if(day == 0){
html.push('<td class="hideSunday"' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}else{
html.push('<td ' + attributesCallbacks({}, opt.dayTdAttrs, today) + '><div ' + attributesCallbacks(todayDivAttr, opt.dayDivAttrs, today) + '>' + showDayHTML(today.time, today.day) + '</div></td>');
}
}
html.push('</tr>');
}
return html.join('');
}
In this function i have added class hideSunday while pushing the element.
The 2nd function is getWeekHead():
function getWeekHead() {
var prepend = opt.showWeekNumbers ? '<th>' + translate('week-number') + '</th>' : '';
if (opt.startOfWeek == 'monday') {
return prepend + '<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>' +
'<th class="hideSunday">' + translate('week-7') + '</th>';
} else {
return prepend + '<th class="hideSunday">' + translate('week-7') + '</th>' +
'<th>' + translate('week-1') + '</th>' +
'<th>' + translate('week-2') + '</th>' +
'<th>' + translate('week-3') + '</th>' +
'<th>' + translate('week-4') + '</th>' +
'<th>' + translate('week-5') + '</th>' +
'<th>' + translate('week-6') + '</th>';
}
}
In this file, I have added class to week-7 header.
CSS:
.hideSunday{display:none;}
Please note, I have not checked all the scenario but it will do trick for you.
I finally ended up by letting the Sundays appear (but completely disabling them).
These questions inspired me :
Moment.js - Get all mondays between a date range
Moment.js: Date between dates
So I created a function as follows which returns an array that contains the "sundays" (or whatever day you provide as dayNumber parameter) in the date range you selected:
function getDayInRange(dayNumber, startDate, endDate, inclusiveNextDay) {
var start = moment(startDate),
end = moment(endDate),
arr = [];
// Get "next" given day where 1 is monday and 7 is sunday
let tmp = start.clone().day(dayNumber);
if (!!inclusiveNextDay && tmp.isAfter(start, 'd')) {
arr.push(tmp.format('YYYY-MM-DD'));
}
while (tmp.isBefore(end)) {
tmp.add(7, 'days');
arr.push(tmp.format('YYYY-MM-DD'));
}
// If last day matches the given dayNumber, add it.
if (end.isoWeekday() === dayNumber) {
arr.push(end.format('YYYY-MM-DD'));
}
return arr;
}
Then I call this function in my code like that:
$('#daterange-2')
.dateRangePicker(configObject2)
.bind('datepicker-change', function(event, obj) {
var sundays = getDayInRange(7, moment(obj.date1), moment(obj.date1).add(selectedDatesCount, 'd'));
console.log(sundays);
$('#daterange-2')
.data('dateRangePicker')
.setDateRange(obj.value, moment(obj.date1)
.add(selectedDatesCount + sundays.length, 'd')
.format('YYYY-MM-DD'), true);
});
This way, I retrieve the amount of sundays in the date range I selected. For example, if there's two sundays in my selection (with sundays.length), I know I have to set two additional workdays to the user selection (in the second date range picker).
Here's the working result:
With the above screenshot, you can see the user selected 4 workdays (5 with sunday but we don't count it). Then he click on the second calendar and the 4 workdays automatically apply.
Here's the result if the period apply over a sunday (we add one supplementary day and Xfor X sundays in the period):
Finally, here's the working fiddle: https://jsfiddle.net/maximelafarie/dnbd01do/21/
I want to thank any person that helped me. The question was hard to explain and to understand.
You can also do it by setting a custom css class and use it in beforeShowDay like below
.hideSunDay{
display:none;
}
beforeShowDay: function(t) {
var valid = t.getDay() !== 0; //disable sunday
var _class = t.getDay() !== 0 ? '' : 'hideSunDay';
// var _tooltip = valid ? '' : 'weekends are disabled';
return [valid, _class];
}
But it only hides the sundays beginning from current day.
Here is a working fiddle
https://jsfiddle.net/dnbd01do/16/

Last array element keeps returning false

I have a time/date converter. When the user enters "130" for example it returns "06/07/2016 01:30:00" when they enter "6 7 16" for example it returns "06/07/2016 00:00:00" but when the user enters "6 7 16 130" for example it returns "06/07/2016 false:00"
Here is my relevant code (can show more if need be):
function checkDateTime(val) {
var nowDate = new Date();
var month, day, year, time;
var ar;
if (eval(val)) {
var tval = val.value;
ar = tval.split(' ');
if (ar.length === 3) { // i.e. if it's supposed to be a date
ar[0] = month;
ar[1] = day;
ar[2] = year;
document.getElementById("FromDate").value = CheckDate(val) + ' ' + '00:00:00';
//checkDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]);
}
//alert(LeftPadZero(ar[0]) + ' ' + LeftPadZero(ar[1]) + ' ' + LeftPadZero(ar[2]));
//alert(CheckDate(ar[0] + ' ' + ar[1] + ' ' + ar[2]));
if (ar.length === 1) { // if it's a time
ar[0] = time;
var MM = nowDate.getMonth() + 1;
var DD = nowDate.getDate();
var Y = nowDate.getFullYear();
var nowDateFormat = LeftPadZero(MM) + '/' + LeftPadZero(DD) + '/' + Y;
alert(ar[0]);
document.getElementById("FromDate").value = nowDateFormat + ' ' + checktime(val) + ':00';
}
if (ar.length === 4) { // if date and time
ar[0] = month;
// alert(ar[0]);
ar[1] = day;
// alert(ar[1]);
ar[2] = year;
// alert(ar[2]);
ar[3] = time;
// alert(ar[3]);
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
// alert(ar[0] + ' ' + ar[1] + ' ' + ar[2] + ' ' + ar[3]);
}
}
}
function CheckDate(theobj) {
var isInvalid = 0;
var themonth, theday, theyear;
var arr;
if (eval(theobj)) {
var thevalue = theobj.value;
arr = thevalue.split(" ");
if (arr.length < 2) {
arr = thevalue.split("/");
if (arr.length < 2) {
arr = thevalue.split("-");
if (arr.length < 2) {
isInvalid = 1;
}
}
}
if (isInvalid == 0) {
themonth = arr[0];
theday = arr[1];
if (arr.length == 3) {
theyear = arr[2];
} else {
theyear = new Date().getFullYear();
}
if (isNaN(themonth)) {
themonth = themonth.toUpperCase();
//month name abbreviation array
var montharr = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
for (i = 0; i < montharr.length; i++) {
//if the first 3 characters of month name matches
if (themonth.substring(0, 3) == montharr[i]) {
themonth = i + 1;
break;
}
}
} else {
if (themonth < 1 || themonth > 12) {
isInvalid = 1;
}
}
}
if (isNaN(themonth) || isNaN(theday) || isNaN(theyear)) {
isInvalid = 1;
}
if (isInvalid == 0) {
var thedate = LeftPadZero(themonth) + "/" + LeftPadZero(theday) + "/" + LeftPadZero(theyear);
return thedate;
} else {
return false;
}
}
}
function checktime(x) {
var tempchar = new String;
tempchar = MakeNum(x);
if (tempchar != '' && tempchar.length < 4) {
//e.g., if they enter '030' make it '0030'
if (tempchar.length == 3) {
tempchar='0' + tempchar;
}
//e.g, if they enter '11' make it '1100'
if (tempchar.length == 2) {
tempchar=tempchar + '00';
}
//e.g, if they enter '6' make it '0600'
if (tempchar.length == 1) {
tempchar='0' + tempchar + '00';
}
}
if (tempchar==null || tempchar == '') {
return false;
}
else {
if (tempchar=='2400') {
return false;
}else{
var tempnum= new Number(tempchar);
var swmin = new Number(tempnum % 100);
var swhour = new Number((tempnum-swmin)/100);
if (swhour < 25 && swmin < 60) {
x = LeftPadZero(swhour) + ":" + LeftPadZero(swmin);
return x;
}
else {
return false;
}
}
}
return false;
/*
if(eval(changecount)!=null){
changecount+=1;
}
*/
}
function MakeNum(x) {
var tstring = new String(x.value);
var tempchar = new String;
var f = 0;
for (var i = 0; i < tstring.length; i++) {
// walk through the string and remove all non-digits
chr = tstring.charAt(i);
if (isNaN(chr)) {
f=f;
}
else {
tempchar += chr;
f++;
}
}
return tempchar;
}
I have tried numerous things to figure out why the time element returns false in an array of length 4, but not an array length 1 for some reason, including setting various alerts and checking the console. I have googled this problem several times and came up empty.
To reiterate, my problem is that the time element returns false in an array of 4, and what I am trying to accomplish is for the user to input a date and time and have them both formatted and displayed correctly.
Can anybody help and/or offer any advice and/or suggestions? Thanks!
Edit: user enters '130' should convert to '06/07/2016(today's date) 01:30:00'
6 7 16 should convert to '06/07/2016 00:00:00'
6 7 16 130 should convert to '06/07/2016 01:30:00'
There seems to be some missing parts here... various functions and whatever input type these ones need are excluded from your post... However, taking a guess, I'm going to say that when you are making your final "checktime" call, rather than passing the full "val" variable, you should just be passing the last chunk of your split input, "ar[3]" in this case. That way, only that piece is evaluated by the function.
IE:
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(val) + ':00';
should be
document.getElementById("FromDate").value = CheckDate(val) + ' ' + checktime(ar[3]) + ':00';
Again, this is just a guess due to the missing pieces.
Edit:
After getting some additional details, the issue DOES seem to be in the data being sent to the checktime function, however, due to the current code setup, the fix is actually just making sure that the data being processed by the checktime function is only the last item in the array... see below for the correction within the checktime function:
tempchar = MakeNum(x);
becomes
tempchar = MakeNum(x).split(' ').pop();

Converting the code below to display the date in european format

the IsDateValid function below validates date in an american format.What do i change to convert it to validate the date in a European format. when the validate works a user is able to enter the date by simply entering a + or - sign depending on what they want i.e. a past date, or a future date.
function IsLeapYear(year) {
//Convert from string to number
year = year - 0;
if ((year/4) != Math.floor(year/4)) return false;
if ((year/100) != Math.floor(year/100)) return true;
if ((year/400) != Math.floor(year/400)) return false;
return true;
} //function IsLeapYear...
function countChar(str, daChar) {
//See how many of 'dachar' are in 'str' and return as daCount
var daCount=0;
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == daChar)
//increment count each time we find daChar in str
daCount++;
}
return daCount;
} //function countChar...
function IsDateValid(dateField, noDateRqrd) {
//If no date is required and they didn't enter one, then go back
if (((typeof noDateRqrd != "undefined") && (dateField.value.length == 0))||dateField.value.length == 0)
return null;
//We're going to check this date so go on
var GoodLength = false;
var msg='';
var daysOfMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var daysOfMonthLY = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
//Make sure they have the right number of '/'
var cCount=countChar(dateField.value,'/');
//force a date value
if (dateField.value.length >= 3) {
//alert('cc: ' + cCount + 'fl: ' + dateField.value.length);
if ((cCount == 1) && (dateField.value.length >= 3) && (dateField.value.length <= 5))
GoodLength=true;
else if ((cCount == 2) && (dateField.value.length >= 4) && (dateField.value.length <= 10))
GoodLength=true;
}
//If the length is good, then let's check the contents of the dateField
if (GoodLength == true) {
var firstslash=dateField.value.indexOf('/')+1; //must add 1 to get real position
var lastslash=dateField.value.lastIndexOf('/')+1;
/****************************
Note: substr is not included in CFStudio so 'substr' will not be bolded & blue
*****************************/
var month=dateField.value.substr(0,firstslash-1);
if ((!isNaN(month)) && (month < 13)){
if (firstslash != lastslash) {
//alert(dateField.value);
var day=dateField.value.substr(firstslash,lastslash-firstslash-1); //lastslash-firstslash+1
//We only need to tell it where to cut off the first char
var year=dateField.value.substr(lastslash);
//Access dates can range from 100 to 9999.
//SQL Server dates can range from 1753 to 9999.
//Since this code can run for either db, we'll use the more restrivtive date of 1753.
//The length test will catch any date > 9999.
if (!isNaN(day)&&!isNaN(year)&&(year.length < 5)){
//If there isn't a year value, then put in the current year
if (year.length == 0) {
//There is no year so we only need to get day
var day=dateField.value.substr(firstslash,lastslash-firstslash-1);
//Since they didn't enter a year, we'll use the current year
var now = new Date();
year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else if ((year.length == 1) || (year.length == 2)) {
var tmpDate = new Date(dateField.value);
//Programmer's Note: entered value of "00" would be return as "1900" by getFullYear
tmpDate_yyyy = tmpDate.getFullYear()-1900; //Get 4 dig date and reindex without centuary
//alert('tmpDate_yyyy: ' + tmpDate_yyyy);
if (tmpDate_yyyy < 100) { //If less than 100, then we're in 20th centuary
if (tmpDate_yyyy < 60) //do 00 to 59 as 20xx
tmpDate.setFullYear(2000 + tmpDate_yyyy); //reset year to 21st centuary
else //do 60 to 99 as 19xx
tmpDate.setFullYear(1900 + tmpDate_yyyy); //reset year to 20th centuary
//Have to do it the hard way or we'll also get day, time, etc. which we don't want here
//getMonth is zero based so it returns a number one less that we want
}
dateField.value = tmpDate.getMonth()+1 + "/" + tmpDate.getDate() + "/" + tmpDate.getFullYear();
} else if ((year.length == 4)&&(year > 1752)) {
dateField.value = day + "/" + Month + "/" + year;
} else {
msg= 'The date you entered is not valid: ' + dateField.value + '.';
}//if
} else {
msg= 'The date you entered is not valid: ' + dateField.value + '.';
} //if
} else {
//There is no year so we only need to get day
var day=dateField.value.substr(firstslash);
if (!isNaN(day)) {
//Since they didn't enter a year, we'll use the current year
var now = new Date();
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else {
msg= 'The day you entered is not valid: ' + dateField.value + '.';
} //if
}
//alert('m: ' + month + ' d: ' + day + ' y:' + year);
if ((day==0)||(IsLeapYear(year) && day > daysOfMonthLY[month-1])||(!IsLeapYear(year) && day > daysOfMonth[month-1]))
msg= 'The date you entered is not valid: ' + dateField.value + '.';
} else {
msg='The month you entered is not valid: ' + month + '.';
}
} else {
if (dateField.value.length == 0) {
msg= 'You must enter enter a valid Date.';
} else if ((dateField.value.toLowerCase() == 'today')||(dateField.value.toLowerCase() == 'now')) {
var now = new Date();
var day=now.getDate();
var month=now.getMonth()+1; //Have to add 1 to get correct month
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else if ((dateField.value.indexOf('+') == 0)||(dateField.value.indexOf('-') == 0)) {
//alert('in: ' + dateField.value + ', NaN: ' + isNaN(dateField.value));
if (!isNaN(dateField.value)) {
var now = new Date();
var nowMS = now.getTime(); //Get the current time in milliseconds
//Add the number of milliseconds in a day times the number of days requested
//Use the Math.floor to make sure we only get whole days in case they add a decimal value
now.setTime(nowMS + Math.floor((dateField.value * 1000*60*60*24)));
var day=now.getDate();
var month=now.getMonth()+1; //Have to add 1 to get correct month
var year=now.getFullYear();
dateField.value = month + "/" + day + "/" + year;
} else
msg= 'The proper format, +#, or -#, with no spaces in between: e.g., "+6", or "-2". You entered: "' + dateField.value + '".';
} else
msg= '146: The date you entered is not valid: "' + dateField.value + '".';
}
if(msg.length > 0) {
if (typeof noDateRqrd == 'undefined') {
var lastLine="Select 'OK' to re-enter value, or 'Cancel' to enter the current date.\n\n"
} else {
var lastLine="Select 'OK' to re-enter value, or 'Cancel' to clear the date.\n\n"
}
var conmsg ="\n\n____________________________________________________\n\n" +
msg +
"\n\n____________________________________________________\n\n" +
"A valid date must contain at least one forward slash '/' as well as a day and a month.\n" +
"If you leave the year blank, then the current year will be inserted.\n\n" +
"The allowable date range is from 1/1/1753 to 12/31/9999.\n\n" +
lastLine
if (confirm(conmsg))
dateField.focus();
else {
if (typeof noDateRqrd == 'undefined') {
//get the current time
var Now=new Date();
dateField.value=Now.getMonth()+1 + "/" + Now.getDate() + "/" + Now.getFullYear();
} else {
dateField.value="";
}
}
return false;
} else
return true;
} //function IsDateValid

Cant get what's the issue with Datepicker?

I'm using smarty template engine. I'm using datepicker js plugin. My HTML code is as follows:
<tr>
<td valign="middle" align="right"><b>From Date </b> : </td>
<td align="left" > <input type="text" style="width:100px;" class="inputfield" name="from_date" id="from_date" value="{$from_date}" maxlength="10"/></td>
<td valign="middle" align="right"><b>To Date </b> : </td>
<td> <input type="text" style="width:100px;" class="inputfield" name="to_date" id="to_date" value="{$to_date}" maxlength="10"/></td>
</tr>
The jQuery function code is as below :
{literal}
<script language="javascript" type="application/javascript">
$(function() {
$( "#from_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
$(function() {
$( "#to_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});
$(document).ready(function() {
$("#questions_listing").tablesorter({
widgets:['zebra'],
// sort on the fourth column and first column, order asc
sortList: [[1,0]]
});
});
$(".submit_form").click(function(e) {
var result = validateDate();
if(!result)
return false;
else
document.questions_filter.submit();
});
</script>
{/literal}
The datepicker.js file is as follows:
/* $(function() {
$( "#cal_from_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
$( "#cal_to_date" ).datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd/mm/yy'
});
});*/
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";
var dayArrayShort = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
var defaultDateSeparator = "/"; // common values would be "/" or "."
var defaultDateFormat = "dmy" // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep)
{
var targetDateField = document.getElementsByName (dateFieldName).item(0);
if (!displayBelowThisObject)
displayBelowThisObject = targetDateField;
if (dtSep)
dateSeparator = dtSep;
else
dateSeparator = defaultDateSeparator;
if (dtFormat)
dateFormat = dtFormat;
else
dateFormat = defaultDateFormat;
var x = displayBelowThisObject.offsetLeft;
var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
var parent = displayBelowThisObject;
while (parent.offsetParent) {
parent = parent.offsetParent;
x += parent.offsetLeft;
y += parent.offsetTop ;
}
drawDatePicker(targetDateField, x, y);
}
function drawDatePicker(targetDateField, x, y)
{
var dt = getFieldDate(targetDateField.value );
if (!document.getElementById(datePickerDivID)) {
// don't use innerHTML to update the body, because it can cause global variables
// that are currently pointing to objects on the page to have bad references
//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
var newNode = document.createElement("div");
newNode.setAttribute("id", datePickerDivID);
newNode.setAttribute("class", "dpDiv");
newNode.setAttribute("style", "visibility: hidden;");
document.body.appendChild(newNode);
}
// move the datepicker div to the proper x,y coordinate and toggle the visiblity
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.position = "absolute";
pickerDiv.style.left = x + "px";
pickerDiv.style.top = y + "px";
pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
pickerDiv.style.zIndex = 10000;
// draw the datepicker table
refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}
function refreshDatePicker(dateFieldName, year, month, day)
{
var thisDay = new Date();
if ((month >= 0) && (year > 0)) {
thisDay = new Date(year, month, 1);
} else {
day = thisDay.getDate();
thisDay.setDate(1);
}
var crlf = "\r\n";
var TABLE = "<table cols=7 class='dpTable'>" + crlf;
var xTABLE = "</table>" + crlf;
var TR = "<tr class='dpTR'>";
var TR_title = "<tr class='dpTitleTR'>";
var TR_days = "<tr class='dpDayTR'>";
var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
var xTR = "</tr>" + crlf;
var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";
var TD_title = "<td colspan=5 class='dpTitleTD'>";
var TD_buttons = "<td class='dpButtonTD'>";
var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
var TD_days = "<td class='dpDayTD'>";
var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' "; // leave this tag open, because we'll be adding an onClick event
var xTD = "</td>" + crlf;
var DIV_title = "<div class='dpTitleText'>";
var DIV_selected = "<div class='dpDayHighlight'>";
var xDIV = "</div>";
// start generating the code for the calendar table
var html = TABLE;
// this is the title bar, which displays the month and the buttons to
// go back to a previous month or forward to the next month
html += TR_title;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, -1, "<") + xTD;
html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
html += TD_buttons + getButtonCode(dateFieldName, thisDay, 1, ">") + xTD;
html += xTR;
// this is the row that indicates which day of the week we're on
html += TR_days;
for(i = 0; i < dayArrayShort.length; i++)
html += TD_days + dayArrayShort[i] + xTD;
html += xTR;
// now we'll start populating the table with days of the month
html += TR;
// first, the leading blanks
for (i = 0; i < thisDay.getDay(); i++)
html += TD + " " + xTD;
// now, the days of the month
do {
dayNum = thisDay.getDate();
TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
if (dayNum == day)
html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
else
html += TD + TD_onclick + dayNum + xTD;
// if this is a Saturday, start a new row
if (thisDay.getDay() == 6)
html += xTR + TR;
// increment the day
thisDay.setDate(thisDay.getDate() + 1);
} while (thisDay.getDate() > 1)
// fill in any trailing blanks
if (thisDay.getDay() > 0) {
for (i = 6; i > thisDay.getDay(); i--)
html += TD + " " + xTD;
}
html += xTR;
// add a button to allow the user to easily return to today, or close the calendar
var today = new Date();
var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
html += TR_todaybutton + TD_todaybutton;
html += "<button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>this month</button> ";
html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>close</button>";
html += xTD + xTR;
// and finally, close the table
html += xTABLE;
document.getElementById(datePickerDivID).innerHTML = html;
// add an "iFrame shim" to allow the datepicker to display above selection lists
adjustiFrame();
}
/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateFieldName, dateVal, adjust, label)
{
var newMonth = (dateVal.getMonth () + adjust) % 12;
var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
if (newMonth < 0) {
newMonth += 12;
newYear += -1;
}
return "<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
}
/**
Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
variables at the beginning of this script library.
*/
function getDateString(dateVal)
{
var dayString = "00" + dateVal.getDate();
var monthString = "00" + (dateVal.getMonth()+1);
dayString = dayString.substring(dayString.length - 2);
monthString = monthString.substring(monthString.length - 2);
switch (dateFormat) {
case "dmy" :
return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
case "ymd" :
return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
case "mdy" :
default :
return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
}
}
/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
var dateVal;
var dArray;
var d, m, y;
try {
dArray = splitDateString(dateString);
if (dArray) {
switch (dateFormat) {
case "dmy" :
d = parseInt(dArray[0], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[2], 10);
break;
case "ymd" :
d = parseInt(dArray[2], 10);
m = parseInt(dArray[1], 10) - 1;
y = parseInt(dArray[0], 10);
break;
case "mdy" :
default :
d = parseInt(dArray[1], 10);
m = parseInt(dArray[0], 10) - 1;
y = parseInt(dArray[2], 10);
break;
}
dateVal = new Date(y, m, d);
} else if (dateString) {
dateVal = new Date(dateString);
} else {
dateVal = new Date();
}
} catch(e) {
dateVal = new Date();
}
return dateVal;
}
function splitDateString(dateString)
{
var dArray;
if (dateString.indexOf("/") >= 0)
dArray = dateString.split("/");
else if (dateString.indexOf(".") >= 0)
dArray = dateString.split(".");
else if (dateString.indexOf("-") >= 0)
dArray = dateString.split("-");
else if (dateString.indexOf("\\") >= 0)
dArray = dateString.split("\\");
else
dArray = false;
return dArray;
}
function updateDateField(dateFieldName, dateString)
{
var targetDateField = document.getElementsByName (dateFieldName).item(0);
if (dateString)
targetDateField.value = dateString;
var pickerDiv = document.getElementById(datePickerDivID);
pickerDiv.style.visibility = "hidden";
pickerDiv.style.display = "none";
adjustiFrame();
targetDateField.focus();
// after the datepicker has closed, optionally run a user-defined function called
// datePickerClosed, passing the field that was just updated as a parameter
// (note that this will only run if the user actually selected a date from the datepicker)
if ((dateString) && (typeof(datePickerClosed) == "function"))
datePickerClosed(targetDateField);
}
function adjustiFrame(pickerDiv, iFrameDiv)
{
// we know that Opera doesn't like something about this, so if we
// think we're using Opera, don't even try
var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
if (is_opera)
return;
// put a try/catch block around the whole thing, just in case
try {
if (!document.getElementById(iFrameDivID)) {
var newNode = document.createElement("iFrame");
newNode.setAttribute("id", iFrameDivID);
newNode.setAttribute("src", "javascript:false;");
newNode.setAttribute("scrolling", "no");
newNode.setAttribute ("frameborder", "0");
document.body.appendChild(newNode);
}
if (!pickerDiv)
pickerDiv = document.getElementById(datePickerDivID);
if (!iFrameDiv)
iFrameDiv = document.getElementById(iFrameDivID);
try {
iFrameDiv.style.position = "absolute";
iFrameDiv.style.width = pickerDiv.offsetWidth;
iFrameDiv.style.height = pickerDiv.offsetHeight ;
iFrameDiv.style.top = pickerDiv.style.top;
iFrameDiv.style.left = pickerDiv.style.left;
iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
iFrameDiv.style.visibility = pickerDiv.style.visibility ;
iFrameDiv.style.display = pickerDiv.style.display;
} catch(e) {
}
} catch (ee) {
}
}
When I tested in firbug it is giving me the error TypeError: $(...).datepicker is not a function
I've included the files reuired i.e. jquery1.9.1 and datepicker .js, but still it's not working. Can anyone help me to resolve this issue?
Your code is just working perfectly! Check out this.
You just missed to include jquery-ui
Try including : <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script> in you <head> tag.
UPDATE: The fiddle is by #Safiuddin

OOP JS: function incrementing date repeatedly, and I don't know why?

Following on from my previous thread, I went on to design the following Objects.
/* --- LEAP Namespace --- */
var LEAP = {};
/* --- LEAP.Schedule Object --- */
LEAP.Schedule = function(){//init
this.weeks = [];
this.calculateWeeks();
};
LEAP.Schedule.prototype.pad = function (n) {
return n>9 ? n : "0"+n;
};
LEAP.Schedule.prototype.calculateWeeks = function(){
this.date = new Date ( 2011, 8, 5 ); // First week of new school year
this.num = 36; // Calendar number of this week
this.weeks.push(new LEAP.Schedule.week(this.date, this.num));
for (var i = 1; i < 51; i++) {
var week = i * 7;
var updated_date = new Date ();
updated_date.setDate(this.date.getDate() + week);
if (this.num > 51) {
this.num = 0;
}
this.num++;
this.weeks.push(new LEAP.Schedule.week(updated_date, this.num));
}
};
LEAP.Schedule.prototype.getWeeks = function(){
return this.weeks;
};
/* --- LEAP.Schedule.week Object --- */
LEAP.Schedule.week = function(n_date, n_week){
this.week = n_week;
this.date = n_date;
this.year = this.date.getFullYear();
var JSMonth = this.date.getMonth();
JSMonth += 1;
this.month = JSMonth;
this.day = this.date.getDate();
};
LEAP.Schedule.week.prototype.getJSDate = function(){
return this.date;
};
LEAP.Schedule.week.prototype.getStartDate = function(){
return this.year + "-" + LEAP.Schedule.pad(this.month) + "-" + LEAP.Schedule.pad(this.day);
};
LEAP.Schedule.week.prototype.getEndDate = function(){
var EndOfWeek = this.date;
EndOfWeek.setDate(this.date.getDate() + 6);
var year = EndOfWeek.getFullYear();
var month = LEAP.Schedule.pad(EndOfWeek.getMonth() + 1);
var day = LEAP.Schedule.pad(EndOfWeek.getDate());
return year + "-" + month + "-" + day;
};
LEAP.Schedule.week.prototype.getLabel = function(){
return "Week " + this.week + ": " + this.day + (this.day==1||this.day==21||this.day==31?"st":this.day==2||this.day==22?"nd":this.day==3||this.day==23?"rd":"th") + " " + ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"][this.month-1] + " " + this.year;
};
I'm now using a <SELECT> box to filter some other data, which works successfully, apart from the fact that every time the $('#filter').change() event is triggered, the dates are being incremented.
WeeklyUpdate.init = function() {
UWA.Data.getJson(WeeklyUpdate.URL + "?cmd=getPointTotals", WeeklyUpdate.getTotalPoints);
var Scheduleobject = new LEAP.Schedule();
var weeks = Scheduleobject.getWeeks();
WeeklyUpdate.displayWeekFilter(weeks);
}
WeeklyUpdate.displayWeekFilter = function(weeks) {
var WeekFilterDisplayHTML = '<select id="filter"><option>Click here</option><option value="all">- All, to date</option>';
var now = new Date();
for (var i = 0; i < weeks.length; i++) {
if (weeks[i].getJSDate() < now) {
var label = weeks[i].getLabel();
WeekFilterDisplayHTML += '<option value="' + i + '">' + label + '</option>';
}
}
WeekFilterDisplayHTML += '</select>';
$('div#filter').html(WeekFilterDisplayHTML);
//WeeklyUpdate.filterPointTotalsByStaff( $(this).val() )
$("select#filter").change( function() { WeeklyUpdate.filterPointTotalsByStaff( weeks, $(this).val() ) } );
}
WeeklyUpdate.filterPointTotalsByStaff = function(weeks, val) {
if (val >= 0 && val != "all") {
var StartDate = weeks[val].getStartDate();
var EndDate = weeks[val].getEndDate();
If I add alert(StartDate + ' // ' + EndDate); after those variables, I can see that the EndDate is being incremented every time, rather than being incremented once and then consistently returning the correct EndDate regardless of how many times it is selected from the SELECT box. The StartDate on the other hand works correctly every time.
What should happen is that this.date (which returns a JS date Object for the week being requested) should be the start of the week, then the getEndDate() function should increment that date by 6 days and return the correct date in a MySQL-compatible format. This shouldn't increment every time its <OPTION> is selected from the SELECT box; it should always return the same date.
I'm guessing that it's something to do with the way I've used EndOfWeek = this.date;, but I don't understand why or how.
Many thanks again.
Probably doesn't matter here but is bad form anyway:
for (i = 1; i < 51; i++) {
The variable i should be declared.
In the statement (my wrapping):
$("select#filter").change( function() {
WeeklyUpdate.filterPointTotalsByStaff( weeks, $(this).val() )
});
You do not show how weeks is initialised or assigned a value. There is a weeks property of LEAP.Schedule instances, but above it is used in the context of a global variable.

Categories