How to sum up the time taken column and display inside total time cell?
Example: If the user select the option from drop down list it will create a table row with start and end time along with time difference. Everything is working fine I need to add additional one more script. The total time should display at the bottom and it has to loop.
var myTime = new Date().toLocaleString(navigator.language, {hour: '2-digit', minute: '2-digit', second: '2-digit'});
function getValue(data)
{
var selectedText = $("#ddselect").find("option:selected").text();
if(selectedText!="None"){
var display = document.getElementById("display");
var newRow = display.insertRow(display.rows.length);
var cell1 = newRow.insertCell(0);
cell1.innerHTML = myTime;
var cell2 = newRow.insertCell(1);
cell2.innerHTML = selectedText;
/* stop time */
var stopTime = new Date().toLocaleString(navigator.language, {hour: '2-digit', minute: '2-digit', second: '2-digit'});
var cell3 = newRow.insertCell(2);
cell3.innerHTML = stopTime;
var timeDifference = timediff(myTime,stopTime);
var cell4 = newRow.insertCell(3);
//cell4.innerHTML = new Date(stopTime.getTime() - myTime.getTime());
cell4.innerHTML = timeDifference;
}
}
function timeobject(t){
a = t.replace('AM','').replace('PM','').split(':');
h = parseInt(a[0]);
m = parseInt(a[1]);
s = parseInt(a[2]);
ampm = (t.indexOf('AM') !== -1 ) ? 'AM' : 'PM';
return {hour:h,minute:m,seconds:s,ampm:ampm};
}
function timediff(start,end){
start = timeobject(start);
end = timeobject(end);
end.hour = (end.ampm === 'PM' && start.ampm !== 'PM' && end.hour < 12) ? end.hour + 12 : end.hour;
hourDiff = Math.abs(end.hour-start.hour);
minuteDiff = end.minute - start.minute;
secondDiff = end.seconds - start.seconds;
if(minuteDiff < 0){
minuteDiff = Math.abs(60 + minuteDiff);
hourDiff = hourDiff - 1;
}
if(secondDiff < 0){
secondDiff = Math.abs(60 + secondDiff);
minuteDiff = minuteDiff - 1;
}
var totDiff = hourDiff+'hr '+ Math.abs(minuteDiff)+"min " + Math.abs(secondDiff) +"sec";
return totDiff;
}
<!DOCTYPE html>
<html>
<body>
<select id="ddselect" onchange="getValue()">
<option value="">None</option>
<option value="1">Initial</option>
<option value="2">Revision</option>
<option value="3">Final</option>
</select>
<table id="display" border="1">
<tr>
<th>Start Time</th>
<th>Activity</th>
<th>Stop Time</th>
<th>Time Taken</th>
</tr>
<table border="1">
<th>Total Time:</th>
<th> </th>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</body>
</html>
I found the solution :)
var myTime = new Date().toLocaleString(navigator.language, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
function getValue(data) {
var selectedText = $("#ddselect").find("option:selected").text();
if (selectedText != "None") {
var display = document.getElementById("display");
var newRow = display.insertRow(display.rows.length);
var cell1 = newRow.insertCell(0);
cell1.innerHTML = myTime;
var cell2 = newRow.insertCell(1);
cell2.innerHTML = selectedText;
/* stop time */
var stopTime = new Date().toLocaleString(navigator.language, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
var cell3 = newRow.insertCell(2);
cell3.innerHTML = stopTime;
var timeDifference = timediff(myTime, stopTime);
var cell4 = newRow.insertCell(3);
//cell4.innerHTML = new Date(stopTime.getTime() - myTime.getTime());
cell4.innerHTML = timeDifference;
}
}
var timeArray = [];
function timeobject(t) {
a = t.replace('AM', '').replace('PM', '').split(':');
h = parseInt(a[0]);
m = parseInt(a[1]);
s = parseInt(a[2]);
ampm = (t.indexOf('AM') !== -1) ? 'AM' : 'PM';
return {
hour: h,
minute: m,
seconds: s,
ampm: ampm
};
}
function timediff(start, end) {
start = timeobject(start);
end = timeobject(end);
end.hour = (end.ampm === 'PM' && start.ampm !== 'PM' && end.hour < 12) ? end.hour + 12 : end.hour;
hourDiff = Math.abs(end.hour - start.hour);
minuteDiff = end.minute - start.minute;
secondDiff = end.seconds - start.seconds;
if (minuteDiff < 0) {
minuteDiff = Math.abs(60 + minuteDiff);
hourDiff = hourDiff - 1;
}
if (secondDiff < 0) {
secondDiff = Math.abs(60 + secondDiff);
minuteDiff = minuteDiff - 1;
}
var timeTaken = hourDiff + ':' + Math.abs(minuteDiff) + ":" + Math.abs(secondDiff);
var totDiff = hourDiff + 'hr ' + Math.abs(minuteDiff) + "min " + Math.abs(secondDiff) + "sec";
timeArray.push(timeTaken);
console.log(addTime(timeArray));
return totDiff;
}
function addTime(arr) {
var pad = function(num) {
return ("0" + num).slice(-2);
}
var totalTime = [];
var totalSeconds = 0;
for (var i = 0; i < arr.length; i++) {
totalTime = arr[i].split(":");
var hrs = parseInt(totalTime[0], 10);
var min = parseInt(totalTime[1], 10);
var sec = parseInt(totalTime[2], 10);
var currDurationSec = sec + (60 * min) + (60 * 60 * hrs);
totalSeconds += currDurationSec;
}
var hours = Math.floor(totalSeconds / 3600);
totalSeconds %= 3600;
var minutes = Math.floor(totalSeconds / 60);
var seconds = totalSeconds % 60;
var sumTime = pad(hours) + ":" + pad(minutes) + ":" + pad(seconds);
document.getElementById('sumoftime').innerHTML = sumTime;
}
<!DOCTYPE html>
<html>
<body>
<select id="ddselect" onchange="getValue()">
<option value="">None</option>
<option value="1">Initial</option>
<option value="2">Revision</option>
<option value="3">Final</option>
</select>
<table id="display" border="1">
<tr>
<th>Start Time</th>
<th>Activity</th>
<th>Stop Time</th>
<th>Time Taken</th>
</tr>
<table border="1">
<th>Total Time:</th>
<th id="sumoftime"> </th>
</tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
</script>
</body>
</html>
I have a date texbox to select a date and by using that selected month, I need to loop through the months. For example, if I select today's date I need to showing March as starting month and loop through the months for n number of times. But the problem I am facing here is, after the month of December, I am getting undefined error.
Any idea how to resolve it ?
Fiddle: https://jsfiddle.net/anoopcr/fyaeyg7r/
HTML:
<div class="inputQL">
<div class="InputQuest">Loan start date</div>
<div>
<input type="date" id="date" class="date"></input>
</div>
<div id="hiddendate" class="hiddendate"></div>
</div>
<div id="table_header" class="table_header">
<table cellpadding="15" border="1">
<tr>
<td width="100" align="center"><b>SI No</b></td>
<td width="100" align="center"><b>month</b></td>
<td width="100" align="center"><b>balance</b></td>
</tr>
</table>
</div>
<div id="table" class="table"> </div>
Javascript :
date.onchange = function() {
table();
}
$(document).ready(function() {
document.getElementById("date").valueAsDate = new Date();
table();
})
function table() {
var mo = new Array(12);
mo[0] = "January";
mo[1] = "February";
mo[2] = "March";
mo[3] = "April";
mo[4] = "May";
mo[5] = "June";
mo[6] = "July";
mo[7] = "August";
mo[8] = "September";
mo[9] = "October";
mo[10] = "November";
mo[11] = "December";
var date = new Date(document.getElementById("date").value);
var day = date.getUTCDate();
var month = mo[date.getUTCMonth()];
var year = date.getFullYear();
document.getElementById("hiddendate").innerHTML = month;
var loanstart = month;
var amnttext = 1;
var payment_counter = 1;
var table = "";
table += "<table cellpadding='15' border='1'>";
var n = 0;
while (amnttext < 24) {
var loanstart = mo[date.getUTCMonth() + n];
//display rows
table += "<table cellpadding='15' border='1'>";
table += "<tr>";
table += "<td width='100'>" + payment_counter + "</td>";
table += "<td width='100'>" + loanstart + "</td>";
table += "<td width='100'>" + amnttext + "</td>";
if (n < 12) {
n++;
} else {
n = 0;
}
amnttext++;
payment_counter++;
table += "</table>";
document.getElementById("table").innerHTML = table;
}
One issue is that you access the array mo out of it's limits in
var loanstart = mo[date.getUTCMonth()+n];
Take the modulo by 12 and that Access Violation should be fixed:
var loanstart = mo[(date.getUTCMonth()+n) % 12];
P.S.: As #Vimarsh oberserved, the condition if (n < 12) can be removed completely when using the modulo.
In your code, when n = 11 you increment it rather than making it 0.
Now n = 12 and you get the error as mo[12] is out of bounds.
You can just change the snippet to
if (n<11) {
n++;
} else {
n=0;
}
Although, I agree #milbrandt's answer is a cleaner way to handle this use case.
I have written code to display the date (month, day, day nr, and year) with javascript and placed it in a ul.
my question is how to build up a li with html tags (so that i can place breaks) in a javascript function because now if i would for example do the following
var output = "<li>" + month_full[monthFull] + "<br/>" + weekDay[day] + "</li>";
return output;
it will output exactly how its shown -> http://gyazo.com/5a67f3dbd7db07254bd38d58116aac7c
you can horizontally scroll through my months. now i would like to build it up like so: http://gyazo.com/adb760c912691a7ce26b1cc40d89d1df
to check my jsfiddle to see what i have now: https://jsfiddle.net/GY22/vqfk8yLL/2/
my javascript code is the following:
<script>
// Get today's current date.
var now = new Date();
console.log(now);
// Calculates the number of the week
var weekNumber = ((now.getDate()<10) ? "0" : "")+ now.getDate();
console.log("The current week number is: " + weekNumber);
// Array list of months.
var month_full = new Array(12);
month_full[0] = "January";
month_full[1] = "February";
month_full[2] = "March";
month_full[3] = "April";
month_full[4] = "May";
month_full[5] = "June";
month_full[6] = "July";
month_full[7] = "August";
month_full[8] = "September";
month_full[9] = "October";
month_full[10] = "November";
month_full[11] = "December";
//console.log(month[3]);
var weekDay = new Array(7);
weekDay[0]= "Su";
weekDay[1] = "Mo";
weekDay[2] = "Tu";
weekDay[3] = "We";
weekDay[4] = "Th";
weekDay[5] = "Fr";
weekDay[6] = "Sa";
function weekNr_Month(date){
var month = date.getUTCMonth();
return month[month];
}
function formatDate(date) {
var month = date.getUTCMonth() +1;
var dayNumber = date.getUTCDate();
var year = date.getUTCFullYear();
var day = date.getUTCDay();
var monthFull = date.getUTCMonth();
return month_full[monthFull] + " " + weekDay[day] + ": " + dayNumber + "-" + month + "-" + year + "; ";
}
console.log(formatDate(new Date()));
var today
function addListItem(){
var createListItem = document.createElement("li");
var outputListItem = document.createTextNode(today);
createListItem.appendChild(outputListItem);
var createUl = document.getElementsByTagName("ul");
createUl[0].appendChild(createListItem);
}
// loop starting from may up untill for months from the set date
for (var i = 1; i < 122; i++){
today = formatDate(new Date(2015, 05, i));
//document.write(today + "<br />");
addListItem();
}
document.getElementById('timeline').
getElementsByTagName('li')[(new Date()).getDate() + 1].className += ' currentDate';
</script>
That is because you are creating a text node instead of html content.
Try this:
var createListItem = document.createElement("li");
createListItem.innerHTML = today;
This question already has answers here:
How do I clear the content of a div using JavaScript? [closed]
(2 answers)
Closed 7 years ago.
I'm making a calendar purely from Javascript, but when then previous and next months are shown current content is still present. It should replace the div content. Also, current date should be the only one with red font displayed.
<html>
<head><script>
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var monthName = getMonthName(month);
var time = now.toLocaleTimeString();
var date = now.getDate();
now = null;
var calElem = document.getElementById("cal");
function febDays(year) {
if (year % 4 == 0) {
return 29;
} else {
return 28;
}
}
function getDays(month, year) {
var days = new Array(12);
days[0] = 31;
days[1] = febDays(year);
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
days[7] = 31;
days[8] = 30;
days[9] = 31;
days[10] = 30;
days[11] = 31;
return days[month];
}
function getMonthName(month) {
var mn = new Array(12);
mn[0] = "January";
mn[1] = "February";
mn[2] = "March";
mn[3] = "April";
mn[4] = "May";
mn[5] = "June";
mn[6] = "July";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function monthName(month) {
var mn = new Array(12);
mn[0] = "Jan";
mn[1] = "Feb";
mn[2] = "Mar";
mn[3] = "Apr";
mn[4] = "May";
mn[5] = "Jun";
mn[6] = "Jul";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function setCal() {
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
function previousMonth() {
document.getElementById('cal').innerHTML = "";
month--;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "January"){
year--;
month = 11;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function nextMonth() {
document.getElementById('cal').innerHTML = "";
month++;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "December"){
year++;
month = 0;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function drawCal(startDay, lastDate, date, monthName, year, month) {
var headerHeight = 50;
var border = 2;
var cellspacing = 4;
var headerSize = "+3";
var colWidth = 60;
var dayCellHeight = 25;
var cellHeight = 40;
var todayColor = "red";
var text = "";
text += '<div id="cal">';
text += '<TABLE BORDER=' + border + ' CELLSPACING=' + cellspacing + '>';
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>';
text += '<FONT SIZE=' + headerSize + '>';
text += monthName + ' ' + year;
text += '</FONT>';
text += '</TH>';
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>';
var closeCol = '</TD>';
var weekDay = new Array(7);
weekDay[0] = "Sunday";
weekDay[1] = "Monday";
weekDay[2] = "Tuesday";
weekDay[3] = "Wednesday";
weekDay[4] = "Thursday";
weekDay[5] = "Friday";
weekDay[6] = "Saturday";
text += '<TR ALIGN="center" VALIGN="center">';
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol;
}
text += '</TR>';
var digit = 1;
var curCell = 1;
for (var row = 1; row <= Math.ceil((lastDate + startDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top">';
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break;
if (curCell < startDay) {
text += '<TD></TD>';
curCell++;
} else {
if (digit == date) {
text += '<TD HEIGHT=' + cellHeight + '>';
text += '<FONT COLOR="' + todayColor + '">';
text += digit + " ";
text += '</FONT>';
text += '</TD>';
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>';
digit++;
}
}
text += '</TR>';
}
text += '</TABLE>';
text += '</CENTER>';
text += '</div>';
text += '<button onclick="previousMonth()"><</button>';
text += '<button onclick="nextMonth()">></button>';
document.write(text);
}
</script></head>
<body onload="setCal()">
</body>
</html>
I think it will be better if you can use a container element and set its content rather than to use document.write()
<html>
<head><script>
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var monthName = getMonthName(month);
var time = now.toLocaleTimeString();
var date = now.getDate();
now = null;
var calElem = document.getElementById("cal");
function febDays(year) {
if (year % 4 == 0) {
return 29;
} else {
return 28;
}
}
function getDays(month, year) {
var days = new Array(12);
days[0] = 31;
days[1] = febDays(year);
days[2] = 31;
days[3] = 30;
days[4] = 31;
days[5] = 30;
days[6] = 31;
days[7] = 31;
days[8] = 30;
days[9] = 31;
days[10] = 30;
days[11] = 31;
return days[month];
}
function getMonthName(month) {
var mn = new Array(12);
mn[0] = "January";
mn[1] = "February";
mn[2] = "March";
mn[3] = "April";
mn[4] = "May";
mn[5] = "June";
mn[6] = "July";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function monthName(month) {
var mn = new Array(12);
mn[0] = "Jan";
mn[1] = "Feb";
mn[2] = "Mar";
mn[3] = "Apr";
mn[4] = "May";
mn[5] = "Jun";
mn[6] = "Jul";
mn[7] = "August";
mn[8] = "September";
mn[9] = "October";
mn[10] = "November";
mn[11] = "December";
return mn[month];
}
function setCal() {
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
function previousMonth() {
document.getElementById('cal').innerHTML = "";
month--;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "January"){
year--;
month = 11;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function nextMonth() {
document.getElementById('cal').innerHTML = "";
month++;
var monthName = getMonthName(month);
var firstDay = new Date(year, month, 1);
var startDay = firstDay.getDay();
firstDay = null;
var days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
if (monthName === "December"){
year++;
month = 0;
monthName = getMonthName(month);
firstDay = new Date(year, month, 1);
startDay = firstDay.getDay();
firstDay = null;
days = getDays(month, year);
drawCal(startDay + 1, days, date, monthName, year, month);
}
}
function drawCal(startDay, lastDate, date, monthName, year, month) {
var headerHeight = 50;
var border = 2;
var cellspacing = 4;
var headerSize = "+3";
var colWidth = 60;
var dayCellHeight = 25;
var cellHeight = 40;
var todayColor = "red";
var text = "";
text += '<div id="cal">';
text += '<TABLE BORDER=' + border + ' CELLSPACING=' + cellspacing + '>';
text += '<TH COLSPAN=7 HEIGHT=' + headerHeight + '>';
text += '<FONT SIZE=' + headerSize + '>';
text += monthName + ' ' + year;
text += '</FONT>';
text += '</TH>';
var openCol = '<TD WIDTH=' + colWidth + ' HEIGHT=' + dayCellHeight + '>';
var closeCol = '</TD>';
var weekDay = new Array(7);
weekDay[0] = "Sunday";
weekDay[1] = "Monday";
weekDay[2] = "Tuesday";
weekDay[3] = "Wednesday";
weekDay[4] = "Thursday";
weekDay[5] = "Friday";
weekDay[6] = "Saturday";
text += '<TR ALIGN="center" VALIGN="center">';
for (var dayNum = 0; dayNum < 7; ++dayNum) {
text += openCol + weekDay[dayNum] + closeCol;
}
text += '</TR>';
var digit = 1;
var curCell = 1;
for (var row = 1; row <= Math.ceil((lastDate + startDay - 1) / 7); ++row) {
text += '<TR ALIGN="right" VALIGN="top">';
for (var col = 1; col <= 7; ++col) {
if (digit > lastDate)
break;
if (curCell < startDay) {
text += '<TD></TD>';
curCell++;
} else {
if (digit == date) {
text += '<TD HEIGHT=' + cellHeight + '>';
text += '<FONT COLOR="' + todayColor + '">';
text += digit + " ";
text += '</FONT>';
text += '</TD>';
} else
text += '<TD HEIGHT=' + cellHeight + '>' + digit + '</TD>';
digit++;
}
}
text += '</TR>';
}
text += '</TABLE>';
text += '</CENTER>';
text += '</div>';
text += '<button onclick="previousMonth()"><</button>';
text += '<button onclick="nextMonth()">></button>';
document.getElementById('calc').innerHTML=text;
}
</script></head>
<body onload="setCal()">
<div id="calc"></div>
</body>
</html>
if you want to clear any HTML element you would just
DO NOT use document.write() it clears the whole page.
It's the document.write() It always stays there no matter what. Try not to use document.write()
use createElement('div') instead. It's much more clean, you can keep track of the elements, and they're static, unless you want them to change. everything is under your control.
document.getElementById('Clear_This_Div_id').innerHTML = '';
This will usually clear the element
Without changing much of the other part of your code, you can just change the
document.write(text);
to
document.getElementsByTagName('body')[0].innerHTML = text;
This will clear off the previous content before putting the new one, since you are putting in the body every time.
i have this
<input class="check-agree" type="checkbox" name="policy_agreement" id="fmCheck2" onclick="toggleAgreeButton();"/>
<input class="hidden-input" type="hidden" value="<?php echo Varien_Date::now(); ?>" name="policy_agreement_date"/>
And jQuery
function toggleAgreeButton() {
jQuery('.button.register').hide();
var isAgree = jQuery('#fmCheck2').attr('checked');
if (isAgree) {
jQuery('#registerBtn').show();
jQuery('.hidden-input').add;
} else {
jQuery('#disabled').show();
}
}
I'd like add date and time to value hidden input after checked, how can I do?
Thks
jsFiddle Demo
var months = new Array(12);
months[0] = "Jan";
months[1] = "Feb";
months[2] = "Mar";
months[3] = "Apr";
months[4] = "May";
months[5] = "Jun";
months[6] = "Jul";
months[7] = "Aug";
months[8] = "Sep";
months[9] = "Oct";
months[10] = "Nov";
months[11] = "Dec";
var d = new Date;
var amOrPm = d.getHours() >= 12 ? "PM" : "AM";
var x = months[d.getMonth("mmm")] + " " + d.getDate() + ", " + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + " " + amOrPm;
jQuery('.hidden-input').val(x);
EDIT - I added the hh:mm:ss AM/PM too.