JavaScript calculator help needed - javascript

I'm currently programming a calculator which is divided into two sections. The first section is a textbox which takes a string (an activity the user has entered). The second section consists of 4 textboxes. Each textbox requires a number as input. In the second section of the calculator, the calculator textboxes are labeled days, hours, minutes, and seconds. The purpose of the calculator is to determine how much money after the activity is complete. The formula for the activity & code is shown below.
MoneyMadeDuringActivity = (NumOfDays * days) + (NumOfHours * hours) + (NumOfMinutes * minutes) + (NumOfSeconds * seconds)
$(document).ready(function () {
/**
* VARIABLES
***/
var activity = $('#txtActivity').text();
var c = new Calculator();
var days = $('#txtDays').text();
var hours = $('#txtHours').text();
var minutes = $('#txtMinutes').text();
var seconds = $('#txtSeconds').text();
var MoneyMadeDuringActivity = (days * c.per_day) + (hours + c.per_hour) + (minutes * c.per_minute) + (seconds * c.per_second);
function listen(event, elem, func) {
if (elem.addEventListener) {
elem.addEventListener(event, func, false);
} else if (elem.attachEvent) {
var r = elem.attachEvent("on"+event, func);
return r;
}
}
listen("click", $("#btnCalculate"), (function() {
$("#CalcOutput").text(
"In the time it takes me to " + activity + ",<br />" + "Barack Obama makes " + "$" + MoneyMadeDuringActivity
);
});
});
My problem occurs with getting the output to work. I can't get anything to be displayed. I have the div tag with an id="CalcOutput", so I don't know why it won't display correctly. Please help.

I saw you're trying to insert html with the text method, this is wrong, you html method instead.
$("#CalcOutput").html(
"In the time it takes me to " + activity + ",<br />Barack Obama makes $" + MoneyMadeDuringActivity
);
EDIT
This way worked for me.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
//mocking up your Calculator class
function Calculator(){
this.per_day = 345665;
this.per_hour = 67845;
this.per_minute = 1234;
this.per_second = 789;
}
$(document).ready(function () {
function calculate(){
var activity = $('#txtActivity').val();
var c = new Calculator();
var days = +$('#txtDays').val();
var hours = +$('#txtHours').val();
var minutes = +$('#txtMinutes').val();
var seconds = +$('#txtSeconds').val();
var MoneyMadeDuringActivity = (days * c.per_day) + (hours + c.per_hour) + (minutes * c.per_minute) + (seconds * c.per_second);
$("#CalcOutput").html(
"In the time it takes me to " + activity + ",<br />Barack Obama makes $" + MoneyMadeDuringActivity
);
}
$("#btnCalculate").click(function() {
calculate();
});
});
</script>
</head>
<body>
activity:
<input type='text' id='txtActivity' value='foobar' /><br/>
days:
<input type='text' id='txtDays' value='3'/><br/>
hours:
<input type='text' id='txtHours' value='12'/><br/>
minutes:
<input type='text' id='txtMinutes' value='34'/><br/>
seconds:
<input type='text' id='txtSeconds' value='37' /><br/>
<button id='btnCalculate'>Calculate</button><br>
<div id="CalcOutput"></div>
</body>
</html>

Related

Start countdown after php page load

I am trying to create a browser training button. When the user clicks the " Brench Press" button his "Strength" increases by a php file that i've set in the form action and it checks some values and inserts values to the database that shows up.
What my problem and what i would like some help with is to implement my clock function that sets a countdown from 30 seconds to 0. This should be a countdown that the users has to watch and wait for untill he can "train" again. So somehow i need to write this clock function to output after the php file has been loaded and not onclick on the button as of now. And also for the clock not to refresh it's countdown on page refresh but keep going.
What i tried to do is to create a session with the function call inside and send it to the site so it loads after the php file has loaded but it doesn't seem to work.
$_SESSION['CountDownBenchPress'] = "<script> countdown(); </script>";
var time = 30;
function countdown()
{
if(time==0)
{
window.location.reload();
}
else
{
tmptime = time;
dayTime = 24*60*60;
hourTime = 60*60;
minutesTime = 60;
days = Math.floor(tmptime/dayTime);
tmptime = tmptime - days*dayTime;
hours = Math.floor(tmptime/hourTime);
tmptime = tmptime - hours*hourTime;
minutes = Math.floor(tmptime/minutesTime);
tmptime = tmptime - minutes*minutesTime;
seconds = tmptime;
tidtext="";
if(days>0)
tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
else if(hours>0)
tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
else
tidtext = minutes + " minutes " + seconds + " seconds";
document.getElementById('timer').innerHTML = tidtext;
time--;
setTimeout("countdown()", 1000);
}
}
<form class="" action="" method="">
<td data-th="Workout"><input type="submit" onclick="countdown()" name="" value="Bench Press"></td>
<div id="timer"></div>
</form>
var time = 30;
function countdown()
{
if(time==0)
{
window.location.reload();
}
else
{
tmptime = time;
dayTime = 24*60*60;
hourTime = 60*60;
minutesTime = 60;
days = Math.floor(tmptime/dayTime);
tmptime = tmptime - days*dayTime;
hours = Math.floor(tmptime/hourTime);
tmptime = tmptime - hours*hourTime;
minutes = Math.floor(tmptime/minutesTime);
tmptime = tmptime - minutes*minutesTime;
seconds = tmptime;
tidtext="";
if(days>0)
tidtext = days+ hours + " hours " + minutes + " minutes " + seconds + " seconds";
else if(hours>0)
tidtext = hours + " hours " + minutes + " minutes " + seconds + " seconds";
else
tidtext = minutes + " minutes " + seconds + " seconds";
document.getElementById('timer').innerHTML = tidtext;
time--;
setTimeout("countdown()", 1000);
}
}
<form class="" action="" method="">
<td data-th="Workout"><input type="button" onclick="countdown()" name="" value="Bench Press"></td>
<div id="timer"></div>
</form>
you must put input type="button" instead of submit. That's because the submit redirects you to the action page that you wrote in the form (in your case, nothing)
EDIT I didn't notice the auto-click part. To solve it, you must modify the body tag as it follows
<body onload="document.getElementById('clickme').click()">
and the button like this
<input type="button" id="clickme" onclick="countdown()" name="" value="Bench Press">

How to show Time With changing minutes and seconds?

I need to show the time in a text type input in a dynamic way, that is to say that it is constantly changing. For this, they recommended me to use the following function, but I have not managed to make the time show correctly. What am I doing wrong ?
Javascript
function new_clock(){
clock = new Date()
hour = clock.getHours()
minutes = clock.getMinutes()
seconds = clock.getSeconds()
print_clock= hour + " : " + minutes + " : " + seconds
document.form_clock.clock_txt.value = print_clock
setTimeout("new_clock()",1000)
}
HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<section onload="new_clock()">
<form name="form_clock">
<input type="text" name="clock_txt" size="10" id="clock_txt">
</form>
The selected response works well, however when implementing the clock, it causes the module actions to load much slower.
Javascript
var today = moment().format('YYYY-MM-DD');
function new_clock(){
clock = new Date() ;
hour = clock.getHours();
minutes = clock.getMinutes() ;
seconds = clock.getSeconds() ;
print_clock= today + " " + hour + ":" + minutes + ":" + seconds;
$("#fecha_registro").val(print_clock);
setInterval(new_clock, 1000);
}
new_clock();
do this https://jsfiddle.net/u1Lkd0ra/
in javascript
function new_clock(){
clock = new Date();
hour = clock.getHours();
minutes = clock.getMinutes();
seconds = clock.getSeconds();
print_clock= hour + " : " + minutes + " : " + seconds;
document.form_clock.clock_txt.value = print_clock;
setTimeout(new_clock,1000);
}
new_clock();
and HTML
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<form name="form_clock">
<input type="text" name="clock_txt" size="10" id="clock_txt">
</form>
Use setInterval method instead of setTimeout. Code that looks like this:
setInterval(function() {
var clock = new Date();
var hour = clock.getHours();
var minutes = clock.getMinutes();
var seconds = clock.getSeconds();
var print_clock = hour + " : " + minutes + " : " + seconds;
console.log(print_clock);
}, 1000);
I haven't really touched javascript, but would setTimeout(new_clock, 1000) work?
This is based on what I read here:
javascript setTimeout() not working
EDIT:
OOOP! I GOT IT!
https://jsfiddle.net/7wkw14wd/
So basically, the function is correct...
The time-out thingo... once the timer is up, will call new_clock()...
But since the time-out thingo is IN the function, you need to start it off before the chain reaction of recursion can begin!
https://jsfiddle.net/chj51hc3/1/
HTML :
<section id="mySection">
<form name="form_clock">
<input type="text" name="clock_txt" size="10" id="clock_txt">
</form>
</section>
Javascript :
$("#mySection").ready(function new_clock() {
clock = new Date() ;
hour = clock.getHours();
minutes = clock.getMinutes() ;
seconds = clock.getSeconds() ;
print_clock= hour + " : " + minutes + " : " + seconds;
$("#clock_txt").val(print_clock);
setInterval(new_clock, 1000);
});
For setTimeout, you need to specify a function and not its name.
Use .ready() instead of onload.
And please use semicolons.
EDIT : Updated fiddle for your code structure

document.lastModified only displays current date?

I've been looking for a way to display the date the page last was updated.
Now I've been searching around, and everything points to the document.lastModified function, but however I've tried to fix it, it always shows the current date.
I've tried this example:
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "-" + (modiDate.getMonth() + 1) + "-" + modiDate.getFullYear();
return showAs
}
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds(); }
else {
Seconds = modiDate.getSeconds(); }
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime }
document.write("Last updated on ");
document.write(lastModified() + " # " + GetTime());
document.write(" [D M Y 24 Hour Clock]"); document.write("");
Or a simple one like this:
<SCRIPT LANGUAGE="JavaScript">
var t = new Date(document.lastModified);
document.write("<I>Last Updated: "+document.lastModified+"</I><BR>");
document.write("<I>Last Updated: "+t+"</I><BR>");
</SCRIPT>
Is there any other way to do this?
.. Without taking a 3 years tech-class?
Press here to see the scripts live
Because you are modifying it currently. Check this out for example.
To make this work based on your requirement, checkout this link and this link
check this it will help u
Put this on the page at the bottom:
<script type="text/javascript" src="js_lus.js"></script>
Name the file whatever you want. Example: js_lus.js Make sure src=""
path is correct for all your pages.
function lastModified() {
var modiDate = new Date(document.lastModified);
var showAs = modiDate.getDate() + "-" + (modiDate.getMonth() + 1) + "-" +
modiDate.getFullYear();
return showAs
}
function GetTime() {
var modiDate = new Date();
var Seconds
if (modiDate.getSeconds() < 10) {
Seconds = "0" + modiDate.getSeconds();
} else {
Seconds = modiDate.getSeconds();
}
var modiDate = new Date();
var CurTime = modiDate.getHours() + ":" + modiDate.getMinutes() + ":" + Seconds
return CurTime
}
document.write("Last updated on ")
document.write(lastModified() + " # " + GetTime());
document.write(" [D M Y 24 Hour Clock]")
document.write("");

javascript coundown " SyntaxError: expected expression, got '.' "

var dateObj = new Date();
var month = dateObj.getUTCMonth() +1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var nowhour = dateObj.getHours();
var nowday = dateObj.getUTCDate();
var hour = "03";
var min = "00";
var hour2 = "18";
var min2 = "00";
var hour3 = "21";
var min3 = "00";
if(hour == 03)
{
day++;
}
document.write(nowhour);
newdate = year + "/" + month + "/" + day;
hourdate = " " + hour + ":" + min;
hourdate2 = " " + hour2 + ":" + min3;
hourdate3 = " " + hour2 + ":" + min3;
$("#bifrost")
if(nowhour > hour && day > nowday)
{
.countdown(newdate + hourdate, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}else if(nowhour > hour2)
{
.countdown(newdate + hourdate2, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}else{
.countdown(newdate + hourdate3, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}
Hello, i wanna make a countdown timer for events. I have 3 different event time,i wanna show up coming event here is my javascript code.
can anyone help me ?
ps: sorry for my bad english.
If countdown is a global function, you do not need the period before the call, just
countdown(parameters ... );
If countdown is a jquery plugin you have, and you are trying to call it on the jQuery object you created before the if statements, you must do it like this
$("#bifrost").countdown(parameters ... );
And repeat the jQuery selector in each of your if statements.
There is built in function setTimeout(function,milliseconds,param1,param2,...). Please see for examples in here.
setTimeout(function_to_do, miliseconds to wait) - will be triggered once;
setInterval(function_to_do, miliseconds to wait) - will be triggered periodically.
By the way - function name can't start with dot - and you have three calls to something .countdown(... There is you error.

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

Categories