Taking inputted value and putting it on a timer - javascript

So I'm making a countdown timer and I'm trying to figure out how to grab the values inputted through the form and put them in the display so the timer can count down from that.
Here's the (probably vastly wrong) JS function I wrote:
function changeTime() {
var h = parseInt(hrs.value);
var m = parseInt(mns.value);
var s = parseInt(scs.value);
if (h < 10) {
h = 0 + h;
};
if (m < 10) {
m = 0 + m;
};
if (s < 10) {
s = 0 + s;
};
$("#time").html() = h + ":" + m + ":" + s;
}
$("#change").click(function() {
changeTime();
})
Here's the form part of the HTML:
<form id="choose">
<input type="text" id="hrs" name="hrs" size="2" maxlength="2" placeholder="h"/>
<input type="text" id="mns" name="mns" size="2" maxlength="2" placeholder="m"/>
<input type="text" id="scs" name="scs" size="2" maxlength="2" placeholder="s"/>
</form>
Here's the whole fiddle. I know the alignment is off, but I'll fix it, I just want help with the JS. Thanks!

The html() setter should be work only if you added HTML string as the argument in the method.
$("#time").html( h + ":" + m + ":" + s );
Although you need to use string concatenation instead of Number addition.
if (h < 10) {
h = '0' + h;
//--^-^--- this should be string
};

Related

javascript simple loop calculation

function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var time = 1;
var dd = document.getElementById("dd").value / 365;
first = 1 + ((bb / 100) / cc);
second = cc * time;
result = aa * Math.pow(first, second);
bb_earn = aa * Math.pow(first, second) - aa;
final = Number(aa) + Number(bb_earn);
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = +newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
I am trying to loop the default value, 20% of default value and sum of default value plus 20% of default value. In next row, default value should be previous final column sum value. I tried above javascript calculation to achieve the desired result. But, I messed up..
Output result is:
1) 12000---14400---14400
2) 12000---16800---14400
3) 12000---19200---14400
4) 12000---21600---14400
5) 12000---24000---14400
But, Output should be:
1) 12000---2400---14400
2) 14400---2880---17280
3) 17280---3456---20736
4) 20736---4147.20---24883.20
5) 24883.20---4976.60---29859.80
It's a bit hard to figure out what you're trying to achieve with the code, based on what you write. It could be written a lot more simple if you merely wanted to take the previous total and add 20% each time. You don't explain what time variable does and what the #cc element does.
Regardless of that, this should output the result you expect.
function calc() {
var aa = document.getElementById("aa").value;
var bb = document.getElementById("bb").value;
var cc = document.getElementById("cc").value;
var dd = document.getElementById("dd").value / 365;
var r = "";
var lastTotal = Number(aa);
for (var i = 0; i < dd; i++) {
var ratio = ((bb / 100) / cc);
var addition = lastTotal * ratio;
var newTotal = lastTotal + addition;
r += i + 1 + ") " + lastTotal + "---" + addition + "---" + newTotal + "<br/>";
r += "";
lastTotal = newTotal;
}
document.getElementById("table").innerHTML += r;
}
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
There is nothing wrong with the for next loop
But i guess everything is wrong with your formulas.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
</head>
<body>
<div> A - <input type="text" id="aa" value="12000" /></div>
<div> B - <input type="text" id="bb" value="20" /></div>
<div> C - <input type="text" id="cc" value="1" /></div>
<div> D - <input type="text" id="dd" value="1825" /></div>
<div> <input type="button" value="Get" onclick="calc();" /></div>
<br/><br/>
<div id="table"></div>
<script>
function calc(){
var aa = document.getElementById("aa").value*1.0;//ensure that we use numbers and not strings
var bb = document.getElementById("bb").value*1.0;
var cc = document.getElementById("cc").value*1.0;
var time = 1.0;
var dd = document.getElementById("dd").value*1 / 365;
first = 1 + ((bb / 100) / cc);//first = 1.2 bb 20 ,cc 1
second = cc * time; // 1*1=1
// i guess here you make a mistake or choose the wrong test datas
var fact=Math.pow(first, second) // fact = 1.2^1
result = aa * fact; //result 14400 = 12000*1.2;
bb_earn = aa * fact - aa; // bb_earn = 1.2 * 12000 -12000 = .2*12000 =2400
final = aa + bb_earn; //final =12000 + 2400 = again 14400
var zz=0;
var r = "";
var lastTotal = aa;
for (var i = 0; i < dd; i++) {
// as you could see thére is by this numbers NO chance to get something like -4147.20
// there are NO AFTER DIGITS in this calculation
//based on the fact result not possible
var newTotal = Number(lastTotal) + Number(bb_earn);
zz = newTotal;
lastTotal = newTotal;
r += i + 1 + ") " + aa + "---" + zz + "---" + final + "<br/>";
r += "";
}
document.getElementById("table").innerHTML += r;
}
</script>
</body>
</html>

Bootstrap dynamic hours refreshing issue

tl;dr : I want to refresh time inside the popover without having to toggle it again (by clicking). When it's opened, it update the time.
I'm trying to make my popover refresh but I can't find a way to do it. I have dynamic hours in it, it needs to change every seconds. It is the only content that will need to be refresh even when the page is active. The other will update if we toggle it, if I need to update it too. I tried to search many ways to do it but couldn't find any clues.
<div class="col-md-8" style="padding-top:50px;position: relative;">
<canvas class="canvas" id="canvas" width="650px" height="450px">Votre
navigateur ne supporte pas le canevas.
</canvas>
 
<input type="image" src="images/plane.png" id="planeimg" data-container="body" data-toggle="popover" data-placement="top"
title="Données du trajet" data-html="true"/>
<!-- POPOVER CONTENT -->
<div id="popover-content" class="hide">
<span>Départ : </span> <span id="departPopover">Montreal</span> <br/>
<span>Arrivée : </span> <span id="arrivePopover">Toronto</span> <br/>
<span>Prochaine ville : </span> <span id="nextCity">Toronto</span> <br/>
<span>Vitesse : 500 km/h</span> <br/>
<span>Temps restant : </span> <span id="timeLeft">2</span> <span>h</span> <br/>
<span>Heure : </span> <span id="timeHours"></span>
</div>
</div>
Here is my Javascript code :
$(function(){
// Enables popover
$("[data-toggle=popover]").popover({
html: true,
content: function() {
return $('#popover-content').html();
}
});
});
// TIME FUNCTION
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('timeHours').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
Thanks for the help guys!
Here's simple solution for updating clock:
function startTime() {
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
// Pad the minutes and seconds with leading zeros
m = ( m < 10 ? "0" : "") + m;
s = ( s < 10 ? "0" : "") + s;
// AM or PM (for 24h delete this)
var time = (h < 12) ? "AM" : "PM";
// 12 hour format (for 24h delete this)
h = (h > 12) ? h - 12 : h;
// Conver an hours form 0 to 12
h = (h == 0) ? 12 : h;
// Visual compose
var display = h + ":" + m + ":" + s + " " + time;
// (for 24h )
// var display = h + ":" + m + ":" + s;
$("#timeHours").html(display);
}
$(document).ready(function(){
setInterval('startTime()', 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="timeHours"></span>
Hope it helps!

How to add two input time values and display it in another input box?

I am getting two durations, current time and previous time from user. now, i want to calculate the total time show it on the third textbox.
<p><span>Current Duration</span><input id="txt1" onblur="sum();" type="text" autocomplete="off" name="current_duration" value="" /></p>
<p><span>Previous Duration</span><input id="txt2" onblur="sum();" type="text" autocomplete="off" name="previous_duration" value="" /></p>
<p><span>Total Duration</span><input id="txt3" type="text" readonly autocomplete="off" name="total_duration" value="" /></p>
<script>
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = result;
}
}
</script>
How can i implement the same? can you guys help me out?
Assumning the separator between time and minutes is '.', this will work. If another separator i needed, just replace the character in toTime() and fromTime()
<p><span>Current Duration</span><input id="txt1" onblur="sum();" type="text" autocomplete="off" name="current_duration" value="" /></p>
<p><span>Previous Duration</span><input id="txt2" onblur="sum();" type="text" autocomplete="off" name="previous_duration" value="" /></p>
<p><span>Total Duration</span><input id="txt3" type="text" readonly autocomplete="off" name="total_duration" value="" /></p>
<script>
function sum() {
var txtFirstNumberValue = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var result = fromTime(txtFirstNumberValue) + fromTime(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('txt3').value = toTime(result);
}
}
function fromTime(time) {
var timeArray = time.split('.');
var hours = parseInt(timeArray[0]);
var minutes = parseInt(timeArray[1]);
return (hours * 60) + minutes;
}
function toTime(number) {
var hours = Math.floor(number / 60);
var minutes = number % 60;
return hours + "." + (minutes <= 9 ? "0" : "") + minutes;
}
</script>
JsFiddle
I have find this from SO.
You can try this:
function sum()
{
var datetime = document.getElementById('txt1').value;
var txtSecondNumberValue = document.getElementById('txt2').value;
var datetime = new Date(datetime).getTime();
var now = new Date(txtSecondNumberValue).getTime();
if( isNaN(datetime) )
{
return "";
}
console.log( datetime + " " + now);
if (datetime < now) {
var milisec_diff = now - datetime;
}else{
var milisec_diff = datetime - now;
}
var days = Math.floor(milisec_diff / 1000 / 60 / (60 * 24));
var date_diff = new Date( milisec_diff );
return days + "d "+ (date_diff.getHours() - 5) + "h " + (date_diff.getMinutes() - 30) + "m";
}

Keep Time Value after closing the browser and calls it again - Javascript?

I asked yesterday about saving a timer value when the browser closes and then start counting again when the user opens it. I've found that using cookies must be a good solution, so i've added the set and getcookie functions, but still i can't get my timer values. This might be easy, but i cant see what's wrong because i'm still too noob in javascript.
Does someone know what i'm doing wrong?
thank you!!
here's the code i have so far:
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head>
<title>Test</title>
<script type="text/javascript">
var sec = 0;
var min = 0;
var hr = 0;
var dias = 0;
var bool = true;
function stopwatch() {
sec++;
if (sec == 60) {
sec = 0;
min += 1;
}
if (min == 60) {
min = 0;
hr += 1;
}
if (hr == 24) {
hr = 0;
dias += 1;
}
totalTime = ((dias<=9) ? "0" + dias : dias) + "d, " + ((hr<=9) ? "0" + hr : hr) + " : " + ((min<=9) ? "0" + min : min) + " : " + ((sec<=9) ? "0" + sec : sec);
document.getElementById("timer").innerHTML = totalTime;
if (bool == true) {
start = setTimeout("stopwatch()", 1000);
}
}
function setCookie(name, value, expires) {
document.cookie = name + "=" + escape(value) + "; path=/" + ((expires == null) ? "" : "; expires=" + expires.toGMTString());
}
function getCookie (name) {
var cname = name + "=";
var dc = document.cookie;
if (dc.length > 0) {
begin = dc.indexOf(cname);
if (begin != -1) {
begin += cname.length;
end = dc.indexOf(";", begin);
if (end == -1) end = dc.length;
return unescape(dc.substring(begin, end));
}
}
return null;
}
var exp = new Date();
exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30));
</script>
</head>
<body onload="stopwatch()">
<div id="timer" name="timer"> </div>
<button onclick="bool = false"; > pause </button>
<button onclick="bool = true;stopwatch();" > resume </button>
<form>
<input type="button" value="Set a Cookie" onClick="setCookie('myCookie',timer.value, exp)">
</form>
<form>
<input type="button" value="Get Cookie Value" onClick="this.form.tf.value = getCookie('myCookie')">
<input type="text" name="tf" size="30">
</form>
</body>
</html>
Firstly, few issues with your code:
Strings shouldn't be used in setTimeouts
Your variables should be initialised as integers, not strings.
Back to your problem, use the unload event to save a cookie with the current time when the user closes the page. Then when the user opens the page again, detect the cookie and continue from where you left off.
If you can't figure out how to pause it, what about getting the Date when the browser closes and then getting the date when it opens again. Calculate the difference and subtract it from the value your timer is at.
I'm just throwing a general idea out there! :D

jQuery Time difference

Hi am making some time calculation in jquery. Do you think am using the best way?
<table width="100%" border="0" cellpadding="0">
<tr>
<td>Departure Time</td>
<td>Arrival Time</td>
<td>Difference</td>
</tr>
<tr>
<td><input name="departure" type="text" class="std1" id="departure" size="10" alt="time"/></td>
<td><input name="arrival" type="text" class="std1" id="arrival" size="10" alt="time"/></td>
<td><input name="duration" type="text" class="std" id="duration" size="10" readonly="readonly" alt="time"/></td>
</tr>
</table>
function hour2mins(timestr) {
var spltd = timestr.split(":");
if (spltd.length == 2) {
return parseInt(parseInt(spltd[0] * 60) + parseInt(spltd[1]));
} else {
return false;
}
}
function mins2hour(instr) {
var hourstr = parseInt(instr / 60);
if (hourstr.toString().length == 1) {
hourstr = "0" + (hourstr + '');
}
var minstr = parseInt(instr % 60);
if (minstr.toString().length == 1) {
minstr = "0" + (minstr + '');
}
return hourstr + ':' + minstr;
}
function tdiff(t1, t2) {
var t1 = hour2mins(t1);
var t2 = hour2mins(t2);
var ret = mins2hour(parseInt(t2 - t1));
if (t2 < t1) {
ret = mins2hour(parseInt(parseInt(t2 + 1440) - t1));
}
return ret;
}
$(function() {
$("input.std1").keyup(function(b) {
$("#duration").val(tdiff($("#departure").val(), $("#arrival").val()));
});
});
link : http://jsfiddle.net/xmQD7/1/
Your code won't work for the following input: "07:09", "07:07". The problem is with your parseInt statement.
You should always pass in 10 as the second parameter, so that it's parsed as a decimal value.
return parseInt(parseInt(spltd[0] * 60, 10) + parseInt(spltd[1], 10));
Also, you don't need to wrap the addition of two parsed integers in a parseInt, so that would be just
return parseInt(spltd[0] * 60, 10) + parseInt(spltd[1], 10);
In mins2hour, you don't need a parseInt here:
var hourstr = parseInt(instr / 60);
and here:
var minstr = parseInt(instr % 60);
I'm guessing you wanted a string as this point (as your var name suggests), so that should have been
var hourstr = "" + (instr / 60);
var minstr = "" + (instr % 60);
There are a few more unnecessary uses of parseInt in your code. I suggest you read the documentation on parseInt - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

Categories