Transform HH MM SS in seconds - javascript

I need to transform 3 form inputs (HH, MM, SS) in seconds with javascript.
I have this code but it has only with 1 form input in seconds : https://jsfiddle.net/94150148/hhomeLc3/
To do this I need a new javascript function.
window.onload = function () {generate()};
function generate() {
var width = 'width=\"' + document.getElementById('width').value + '\" ';
var height = 'height=\"' + document.getElementById('height').value + '\" ';
var ytid = "videoID";
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
if (start !== "") {
if(ytid === document.getElementById('ytid')) {
ytid += '?start=' + start;
}
else {
ytid += '&start=' + start;
}
}
if (end !== "") {
if (ytid === document.getElementById('ytid')) {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
document.getElementById('embedcode').value = '<iframe ' + width + height +
'src=\"https://www.youtube.com\/embed\/' + ytid +
'\" frameborder=\"0\"><\/iframe>';
}
function clearall() {
document.getElementById('width').value = 550;
document.getElementById('height').value = 315;
document.getElementById('start').value = "";
document.getElementById('end').value = "";
}
The jsFiddle to play with what I need : https://jsfiddle.net/94150148/ybmkcyyu/

https://jsfiddle.net/ybmkcyyu/3/
EDIT:
Do not display start and end when value is 0
https://jsfiddle.net/ybmkcyyu/6/
EDIT2:
https://jsfiddle.net/ybmkcyyu/7/
if (start !== "") {
ytid += '?start=' + start;
}
if (end !== "") {
if (start == "") {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
You just need to get value of every fields, as int, then add it with the formula: ((hours * 60) + minutes ) * 60 + secondes
And you might ensure that the result is a number. (if user enter a char instead of a number, it should not display something wrong)
var starth = parseInt(document.getElementById('starth').value);
var startm = parseInt(document.getElementById('startm').value);
var starts = parseInt(document.getElementById('starts').value);
var endh = parseInt(document.getElementById('endh').value);
var endm = parseInt(document.getElementById('endm').value);
var ends = parseInt(document.getElementById('ends').value);
var start = (((starth * 60) + startm) * 60) + starts;
if(isNaN(start) || start === 0)
start = "";
var end = (((endh * 60) + endm) * 60) + ends;
if(isNaN(end) || end === 0)
end = "";
/* (...) */

JS is generally quite good at math.
sHour = document.getElementById('starth').value,
sMin = document.getElementById('startm').value,
sSec = document.getElementById('starts').value,
sTime = (sHour * 3600) + (sMin * 60) + sSec;
https://jsfiddle.net/link2twenty/ybmkcyyu/4/

Related

time diffrence in double digit

i want to display TravelTimeHoursDiff and TravelTimeMinutesDiff in double digit now my time is shown as 7:0 i want to display like 07:00
if ($scope.DispatchStatus.ArrivalTime != undefined){
var today = $rootScope.getSysDate().split(" ");
var timeArrival = new Date(today[0] + ' ' + $scope.DispatchStatus.ArrivalTime);
var TravelTime = new Date(today[0] + ' ' + $scope.Route.TravelTime);
var timeArrivalHours = timeArrival.getHours();
var TravelTimeHoursDiff = timeArrivalHours - TravelTime.getHours() ;
var TravelTimeMinutesDiff = (timeArrival.getMinutes() - TravelTime.getMinutes());
if(TravelTimeHoursDiff < 0 || (TravelTimeHoursDiff <= 0 && TravelTimeMinutesDiff < 0) || (TravelTimeHoursDiff == 0 && TravelTimeMinutesDiff == 0)){
$scope.formvalidationbit = $scope.DispatchStatusAddForm[fieldName].$invalid = true;
angular.element('#' + fieldName).addClass('ng-invalid');
angular.element('#' + fieldName).removeClass('ng-valid');
$scope.DispatchStatusAddForm.$valid = false;
var errorbit = 1;
}else{
if (isNaN(TravelTimeHoursDiff)) {
TravelTimeHoursDiff = '--';
}
if (isNaN(TravelTimeMinutesDiff)) {
TravelTimeMinutesDiff = '--';
}
if(TravelTimeMinutesDiff <0){
TravelTimeMinutesDiff = TravelTimeMinutesDiff * (-1);
}
$scope.TravelTime = TravelTimeHoursDiff + ':' + TravelTimeMinutesDiff;
}
}
Just add leading 0 to values smaller then 10, something like:
let addLeadingZero(v){
return v < 10 ? ("0" + v) : v;
}
$scope.TravelTime = addLeadingZero(TravelTimeHoursDiff) + ':' + addLeadingZero(TravelTimeMinutesDiff);

JS AM/PM times always show AM

I am making a simple time calculator in javascript. I have converted the times into 12-hour instead of 24 hour time for simplicity, however the code I have for calculating am/pm always shows am. Any reason why this would be happening?
Here is my code:
function solveTime(x) {
var suffixSolve = (utcHours + x) % 24;
var suffix = "am";
if (utcHours > 12) {
var suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
and here is the code behind utcHours
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
Example here: http://codepen.io/markgamb/pen/gwGkbo
The issue is you should be checking whether suffixSolve is greater than 12 instead of utcHours, because utcHours does not change due to the value of x. Since you can shift the hours forward and backwards, I created a variable shift to handle that.
function solveTime(x) {
if (x < 0) {
var shift = 24 + x;
} else {
var shift = x;
}
var suffixSolve = (utcHours + shift) % 24;
var suffix = "am";
if (suffixSolve > 12) {
suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
solveTime(4);
solveTime(0);
solveTime(-8);
<div id="4"></div>
<div id="-8"></div>
<div id="0"></div>

Working on a clock script. I need to add a Zero in front of single digits

As easy as it may sound to a seasoned coder. I am a newbie trying to implement this on my clock page. It can contain errors. The idea is to generate a zero in front of single digits (like "02" instead of "2") for display purposes. It works fine with double digits.
This is what I got, but doesn't do the trick. Includes commented lines of different tries I have done. I would appreciate any input guys.
<script>
$(function() {
getdata();
myinterval = setInterval(getdata, 30000);
});
function getdata(){
var dt = new Date();
console.log(dt.getMinutes());
var myhr = dt.getHours();
var mymin = dt.getMinutes();
//if(myhr < 10) myhrstr = '0' + myhr.toString(); else myhrstr = myhr.toString();
//if(myhr.toString().length < 2) myhrstr = '0' + myhr.toString(); else myhrstr = myhr.toString();
//if(myhr.toString().length < 2) myhr = "0"+myhr;
if(myhr.toString().length == 1) myhrstr = "0" + myhr.toString(); else myhrstr = myhr.toString();
//if(mymin < 10) myminstr = '0' + mymin.toString(); else myminstr = mymin.toString();
//if(mymin.toString().length < 2) myminstr = '0' + mymin.toString(); else myminstr = mymin.toString();
//if(mymin.toString().length < 2) mymin = "0"+mymin;
if(mymin.toString().length == 1) myminstr = "0" + mymin.toString(); else myminstr = mymin.toString();
var mystr = myhrstr + myminstr;
$.ajax(
{
url:"clock.php?action=getdata&dt="+mystr,
success:function(result){
$('#content').html(result);
}
}
);
}
</script>
What makes you think your code isn't working? It works fine.
Here's a demo:
function FakeDate() {
this.getHours = function() {
return Math.round(Math.random() * 23);
}
this.getMinutes = function() {
return Math.round(Math.random() * 59);
}
}
var dt = new FakeDate(); // use fakeDate for random time generations
var myhr = dt.getHours();
var mymin = dt.getMinutes();
if (myhr.toString().length == 1) myhrstr = "0" + myhr.toString();
else myhrstr = myhr.toString();
if (mymin.toString().length == 1) myminstr = "0" + mymin.toString();
else myminstr = mymin.toString();
var mystr = myhrstr + myminstr;
console.log(mystr);
One way you can simplify this code is, since you are not using the numeric values, you can call toString right away on the getHours and getMinutes methods. For the same reason there's also no need for extra variables to hold the string values, you can just use the same variable when appending the "0".
// get the strings representing hours and minutes
var myhr = dt.getHours().toString();
var mymin = dt.getMinutes().toString();
// prepend them with zeros if needed
if (myhr.length == 1) myhr = "0" + myhr;
if (mymin.length == 1) mymin = "0" + mymin;
// concatenate them to a 4 digit value
var mystr = myhr + mymin;
Here's a demo:
function FakeDate() {
this.getHours = function() {
return Math.round(Math.random() * 23);
}
this.getMinutes = function() {
return Math.round(Math.random() * 59);
}
}
var dt = new FakeDate(); // use fakeDate for random time generations
// get the strings representing hours and minutes
var myhr = dt.getHours().toString();
var mymin = dt.getMinutes().toString();
// prepend them with zeros if needed
if (myhr.length == 1) myhr = "0" + myhr;
if (mymin.length == 1) mymin = "0" + mymin;
// concatenate them to a 4 digit value
var mystr = myhr + mymin;
console.log(mystr);
simple trick to pad single digit with zero
('0' + 1).slice(-2) // 01
('0' + 23).slice(-2) // 23
var mystr;
if(myhr < 10 ) {
mystr = "0" + myhr.toString();
} else {
mystr = myhr.toString();
}
if (mymin < 10) {
mystr += ":0" + mymin.toString();
} else {
mystr += ":" + mymin.toString();
}

Sum of value in label having same class

I am trying to add all values of class tmpcpa and place result in final_cpa but final_cpa always return 0.
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
Surprisingly when i view source code in browser HTML appears as
<label class="tmpcpa">0</label> but when i do inspect element it shows as
<label class="tmpcpa">30.0</label>
Update here is the whole JS. HTML calls process function which ultimately calls calculate_final_cpa()
//"use strict";
function process(arr) {
document.getElementById('txtgrade' + arr[0] + arr[1] + arr[2]).innerHTML = show_grade(document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value);
if (validateForm(arr)) {
var module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + arr[2]).value;
var module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + arr[2]).innerHTML;
if (!isNaN(module_percentage) || !isNaN(module_credit)) {
module_percentage = 0;
module_credit = 0;
var total_credit_semester = 0;
var sum_module_percentage_x_credit = 0;
for ( i= 2 ; i <= arr[3] + 1 ; i++) {
module_percentage = +document.getElementById('txtpercentage' + arr[0] + arr[1] + i).value;
module_credit = +document.getElementById('txtcredit' + arr[0] + arr[1] + i).innerHTML;
sum_module_percentage_x_credit += module_percentage * module_credit;
total_credit_semester += module_credit;
}
//console.log(module_percentage);
var spa = sum_module_percentage_x_credit / total_credit_semester;
spa = spa.toFixed(1);
document.getElementById('spa' + arr[0] + arr[1]).innerHTML = spa;
calculate_cpa(arr);
}
}
}
function validateForm(arr) {
var isValid = true;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' :input').each(function () {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
/*
* Works for 2 semester per level and 3 year course (optimize later)
*/
function calculate_cpa(arr) {
var isValid = true;
for ( i= 1 ; i <= 2 ; i++) {
var spa = document.getElementById('spa' + arr[0] + i).innerHTML;
if (spa == "N/A") {
isValid = false;
}
}
if (isValid) {
var total_credit_level = 0;
var total_spa_x_credit = 0;
for ( i= 1 ; i <= 2 ; i++) {
var arr2= [arr[0], i];
var spa = +document.getElementById('spa' + arr[0] + i).innerHTML;
total_spa_x_credit += spa * getcredits(arr2);
total_credit_level += getcredits(arr2);
}
var cpa = total_spa_x_credit / total_credit_level;
cpa = cpa.toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa;
var level = +document.getElementById('level' + arr[0]).innerHTML
var tmp_cpa = ((level / 100) * cpa).toFixed(1);
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label class="tmpcpa">' + tmp_cpa + "</label>" +' For Final' + ')';
var final_cpa = calculate_final_cpa();
console.log(final_cpa);
if (final_cpa != 0) {
var award = show_award(final_cpa);
document.getElementById('award').innerHTML = award;
document.getElementById('finalcpa').innerHTML = final_cpa;
}
}
}
function getcredits(arr) {
var sum = 0;
var tbl_id = 'tbl_semester' + arr[0] + arr[1];
$('#' + tbl_id + ' .sum').each(function () {
sum += parseInt($(this).text())||0;
});
return sum;
}
function show_grade(module_percentage) {
if (isNaN(module_percentage)) {
return 'N/A';
}
if (module_percentage >= 70 && module_percentage <= 100) {
return 'A';
} else if (module_percentage >= 60 && module_percentage < 70) {
return 'B';
} else if (module_percentage >= 50 && module_percentage < 60) {
return 'C';
} else if (module_percentage >= 40 && module_percentage < 50) {
return 'D';
} else {
return 'F';
}
}
function show_award(cpa) {
if (isNaN(cpa)) {
return 'N/A';
}
if (cpa >= 70 && cpa <= 100) {
return 'First Class with Honours';
} else if (cpa >= 60 && cpa < 70) {
return 'Second Class First Division with Honours';
} else if (cpa >= 50 && cpa < 60) {
return 'Second Class Second Division with Honours';
} else if (cpa >= 45 && cpa < 50) {
return 'Third Class with Honours';
} else if (cpa >= 40 && cpa < 45) {
return 'Pass';
} else if (cpa < 40) {
return 'No award';
}
}
you need to be sure you are calling the function after the document is ready.
Also, you are using unassigned value.
</body>
<script>
function calculate_final_cpa() {
var final_cpa = 0;
$('.tmpcpa').each(function () {
if ($(this).val() != 0)
final_cpa += parseInt($(this).text()) || 0;
});
return final_cpa;
}
$(document).ready(function(){
var final_cpa = calculate_final_cpa();
document.getElementById('cpa' + arr[0]).innerHTML = cpa + '(' + '<label id="tmpcpa">' + final_cpa + "</label>" +' For Final' + ')';
console.log(final_cpa);
});
</script>

Jquery mobile input in collapsilble problem

I have a list of collapsible times like in screen shot.. and a droplist.. in drop list you can choose the time how collapsible will separate times.. When i open activity first time...it's working fine but when i choose another time in droplist and he update collapsibles input loses their style and not working..
here is droplist change event->>
$('#timeDropList').change(function() {
$('div.addedEntry').remove();
drawTemplate();
});
and here is draw collapsibles function->>
function drawTemplate() {
var selectedValue = parseInt($('#timeDropList').val());
var textProjectName = '<input type="text" class="projectName" value="" />';
var textProjectData = '<input style="height:50px;" type="text" class="projectEntry" value="" />';
var timespan;
if ($('.div-cell').hasClass('tapped')) {
var calToScheDate = $('.div-cell.tapped').find('.dayNumberCellValue')
.attr('data-a');
var calToScheMonth;
var calToScheDay;
if (calToScheDay = calToScheDate.substring(6, 8) < 10) {
calToScheDay = calToScheDate.substring(7, 8);
} else {
calToScheDay = calToScheDate.substring(6, 8);
}
if (calToScheMonth = calToScheDate.substring(4, 6) < 10) {
calToScheMonth = calToScheDate.substring(5, 6);
} else {
calToScheMonth = calToScheDate.substring(4, 6);
}
timespan = new Date(calToScheDate.substring(0, 4), calToScheMonth,
calToScheDay, 9, 0);
} else {
timespan = new Date();
timespan = new Date(timespan.getFullYear(), timespan.getMonth(),
timespan.getDate(), 9, 0);
}
while (timespan.getHours() < 18 || timespan.getHours() == 18
&& timespan.getMinutes() == 0) {
var hoursFrom = timespan.getHours();
var minsFrom = timespan.getMinutes();
if (minsFrom < 10) {
minsFrom = "0" + minsFrom;
}
if (hoursFrom < 10) {
hoursFrom = "0" + hoursFrom;
}
var hoursTo = timespan.getHours();
var minsTo = timespan.getMinutes() + selectedValue
if (minsTo == 60) {
minsTo = "00";
hoursTo++;
} else if (minsTo < 10) {
minsTo = "0" + minsTo;
}
var collDiv = '<div class="addedEntry" data-theme="c" data-role="collapsible" id='+hoursFrom+minsFrom+hoursTo+minsTo+' data-collapsed="true"><h3 class="results-header">'
+ hoursFrom
+ ":"
+ minsFrom
+ " - "
+ hoursTo
+ ":"
+ minsTo +'</h3>' + '</div>';
$('.spanTimetable').append(collDiv);
timespan.setMinutes(timespan.getMinutes() + selectedValue);
}
$('.addedEntry').append(textProjectName);
$('.addedEntry').append(textProjectData);
$('.results-header').append('<img class="checkOrCross" />');
$('#timetable .addedEntry').collapsible({
refresh : true
});
}
You will need to refresh the jQM using .page()
Maybe try:
$('#timeDropList').change(function() {
$('div.addedEntry').remove();
drawTemplate();
});
$('#name of your page').page();

Categories