storing user input as var - javascript

So this is a timer that computes orders per hour. when i hard code the orders everything works the way i want it. but i can't seem to figure how to get user input to set the amount of orders. this is what I've been trying and it is not working. any ideas??
<html>
<body>
<p><strong>Time Elapsed:</strong><span id="time-elapsed"</span></p>
<button onclick="openFunc()">Start Time</button>
<button onclick="myStopFunction()">Stop time</button><br><br>
<input type="text" id="orderAmount"><br>Enter Number of Orders</input><br><br>
<button onclick="calculate(timeElapsed, orders)">Calculate...</button>
<script>
var timeElapsed = 0;
var myVar = '';
var average = 0;
var orders = document.getElementById("orderAmount").innerHTML += orders;
function openFunc(){
start();
}
function calculate(time, _orders) {
var avg = _orders/(time/_orders);
if (avg<1){
avg = 1;
}
document.write(avg + " Bags per Hour");
}
function start() {
if ( myVar != "" ) {
console.log('timer is running');
return;
}
clearInterval(myVar);
myVar = setInterval(function(){
myTimer()
}, 1000);
}
function myTimer() {
timeElapsed += 1;
document.getElementById("time-elapsed").innerHTML = formatTime(timeElapsed);
}
function formatTime(time) {
var hours = formatNumber(Math.floor(time/3600))
var minutes = formatNumber(Math.floor(time/60));
var seconds = formatNumber(time%60);
//console.log('minutes: ', minutes);
//console.log('seconds: ', seconds);
return hours + ":" + minutes + ":" + seconds
}
function formatNumber(number) {
if ( number < 10 ) {
return 0 + '' + number
}
return number
}
function myStopFunction() {
clearInterval(myVar);
myVar = "";
}
</script>
</body>
</html>

This is how you get user input from text field with orderAmount id:
var orders = document.getElementById("orderAmount").value;

Related

Add value from textbox to counter

I'm learning javascript and I want to create a simple clock. I want for user to be able to change minutes by entering a number in textbox and pressing a button, so when that number is displayed and when the seconds are counted to 60, that displayed number increase by 1, my code won't work, help pls:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
return seconds = 0;
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
return minutes2 = 0;
}
rezultat = (seconds + minutes2 + minutes);
el2.innerText = rezultat;
}
var cancel = setInterval(incrementMinutes, 60000);
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>
You have a few problems in your code. The main mistake is that your variable minutes is not defined in the function incrementMinutes() where you are trying to use it. You have to calculate it again.
Other improvements that you can make are:
Remove the return in your incrementSeconds and incrementMinutes function
Have only 1 setInterval, and call incrementMinutes when seconds reach 60.
You can see a snippet here below:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
incrementMinutes();
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
minutes2 = 0;
}
rezultat = (minutes2 + parseInt(document.querySelector("#value").value));
el2.innerText = rezultat;
}
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
To show here the behavior I made a minute to 5 seconds.
As a formatting improvement, if you want to show in result min:sec you can do this
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
To build the string with leading zeros.
I have removed the returns because they were not neccessary you can inside reset the value there is no need to return it.
var seconds = 0;
var min = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var secCounter = document.getElementById("seconds-counter");
var mintCounter = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
}
secCounter.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
function incrementMinutes() {
min += 1;
if (min === 60) {
min = 0;
}
tempMin = min;
tempSec = seconds;
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
rezultat = (min+":"+seconds);
mintCounter.innerText = rezultat;
min = tempMin;
seconds = tempSec;
}
// for debugging to 5 sec
var cancel = setInterval(incrementMinutes, 5000);
dugme.addEventListener("click", function() {
var inpMinutes = parseInt(document.querySelector("#value").value);
min = inpMinutes;
mintCounter.innerText = min;
})
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>

javascript check for specific characters

I am trying to create a timer in javascript, and I have got it working, however I am trying to validate the users input, for the time. Currently it will accept anything as long as the inputbox is not empty. But I am wanting to only allow numbers, colon (:) and periods (.), I have looked at several questions, but most seem to be only checking for all text characters.
Here is the working code: https://jsfiddle.net/hLqayL1w/
OR
HTML:
<div class="maincont">
<h2>Please enter a amount of time</h2>
<p id="timer">0:00</p>
<div class="container">
<input id="request" type="text" placeholder="Time">
<button type="submit" class="click">Start timer</button>
</div>
<P id="cancelbutton" class="cancel">Cancel timer</P>
</div>
JS:
$(document).ready(function() {
$('#cancelbutton').hide();
});
$('.click').click(function() {
var conts = $('#request').val();
if ($('#request').val() === "") {
return;
}
$('.container').hide();
$('#cancelbutton').fadeIn('slow');
var rawAmount = $('#request').val();
var cleanAmount = rawAmount.split(':');
var totalAmount = parseInt(cleanAmount[0] | 0) * 60 + parseInt(cleanAmount[1] | 0);
$('#request').val(" ");
var loop, theFunction = function() {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
$('#cancelbutton').hide();
$('.container').fadeIn('slow');
}
var minutes = parseInt(totalAmount / 60);
var seconds = parseInt(totalAmount % 60);
if (seconds < 10)
seconds = "0" + seconds;
$('#timer').text(minutes + ":" + seconds);
$('#cancelbutton').click(function() {
totalAmount = 1
});
};
var loop = setInterval(theFunction, 1000);
})
In your example you just check if the input is an empty string lets change that so we check if it matches an regular expression:
if (!$('#request').val().match(/[0-9:.]/gi)) {
return;
}
We make it look for numbers,colons and dots everything else will not match and the return will run.
Here is an working example.
(This is just an quick and dirty example it is not showcasing that the regex should be written in this way, there probably are better ways to write this)
How about this?
$('#request').keyup(function() {
var el = $(this),
val = el.val();
el.val(val.replace(/[^\d\:.]/gi, ""));
}).blur(function() {
$(this).keyup();
});
It will check check if the input is number/./:, if not it will remove it live.
$(document).ready(function() {
$('#cancelbutton').hide();
});
$('#request').keyup(function() {
var el = $(this),
val = el.val();
el.val(val.replace(/[^\d\:.]/gi, ""));
}).blur(function() {
$(this).keyup();
});
$('.click').click(function() {
var conts = $('#request').val();
if ($('#request').val() === "") {
return;
}
$('.container').hide();
$('#cancelbutton').fadeIn('slow');
var rawAmount = $('#request').val();
var cleanAmount = rawAmount.split(':');
var totalAmount = parseInt(cleanAmount[0] | 0) * 60 + parseInt(cleanAmount[1] | 0);
$('#request').val(" ");
var loop, theFunction = function() {
totalAmount--;
if (totalAmount == 0) {
clearInterval(loop);
$('#cancelbutton').hide();
$('.container').fadeIn('slow');
}
var minutes = parseInt(totalAmount / 60);
var seconds = parseInt(totalAmount % 60);
if (seconds < 10)
seconds = "0" + seconds;
$('#timer').text(minutes + ":" + seconds);
$('#cancelbutton').click(function() {
totalAmount = 1
});
};
var loop = setInterval(theFunction, 1000);
})

JS function stopwatch application confuses the user

I wrote a javascript application but I end up with a total confusion. This js application needs to run in minutes, seconds, and hundredths of seconds. The part about this mess is when the stopwatch show, in this case 03:196:03. Here is my confusion. When the stopwatch shows 196, is it showing hundredth of seconds? Does anybody can check my function and tell me what part needs to be corrected in case that the function is wrong?
<html>
<head>
<title>my example</title>
<script type="text/javascript">
//Stopwatch
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
document.getElementById("countDown").disabled = true;
document.getElementById("resetCountDown").disabled = true;
document.getElementById("start").innerHTML = "Stop";
} else {
run = 0;
document.getElementById("start").innerHTML = "Resume";
}
}//End function startWatch
function watchReset() {
run = 0;
time = 0;
document.getElementById("start").innerHTML = "Start";
document.getElementById("output").innerHTML = "00:00:00";
document.getElementById("countDown").disabled = false;
document.getElementById("resetCountDown").disabled = false;
}//End function watchReset
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
var min = Math.floor(time/10/60);
var sec = Math.floor(time/10);
var tenth = time % 10;
if (min < 10) {
min = "0" + min;
}
if (sec <10) {
sec = "0" + sec;
} else if (sec>59) {
var sec;
}
document.getElementById("output").innerHTML = min + ":" + sec + ":0" + tenth;
timeIncrement();
},10);
}
} // end function timeIncrem
function formatNumber(n){
return n > 9 ? "" + n: "0" + n;
}
</script>
</head>
<body>
<h1>Stopwatch</h1>
<p id="output"></p>
<div id="controls">
<button type="button" id ="start" onclick="startWatch();">Start</button>
<button type="button" id ="reset" onclick="watchReset();">Reset</button>
</div>
</body>
</html>
Your code is totally weird!
First you're using document.getElementById() for non-existing elements: maybe they belong to your original code and your didn't posted it complete.
Then I don't understand your time-count method:
you make timeIncrement() to be launched every 10 ms: so time/10 gives you a number of milliseconds
but you compute min and sec as if it was a number of seconds!
From there, all is wrong...
Anyway IMO your could make all that simpler using the getMilliseconds() function of the Date object.
Try this:
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
var time = 0;
var started;
var run = 0;
function startWatch() {
if (run == 0) {
run = 1;
timeIncrement();
} else {
run = 0;
}
}
function watchReset() {
run = 0;
time = 0;
document.getElementById("output").innerHTML = "00:00:00";
}
function timeIncrement() {
if (run == 1) {
setTimeout(function () {
time++;
document.getElementById("output").innerHTML = [
Math.floor(time/100/60 % 60),
Math.floor(time/100 % 60),
time % 100
].map(formatNumber).join(':')
timeIncrement();
},10);
}
}
function formatNumber(n){
return (n < 10 ? "0" : "") + n;
}
startWatch()
<div id="output"></div>

Having trouble with Javascript Stopwatch

I'm working on a stopwatch, and this is my code for it. It makes perfect sense for me, but doesn't want to update for some reason.
HTML:
<ul>
<li id="hour">0</li>
<li>:</li>
<li id="min">0</li>
<li>:</li>
<li id="sec">0</li>
</ul>
JS:
var sec = document.getElementById("sec").value,
min = document.getElementById("min").value,
hour = document.getElementById("hour").value;
function stopWatch(){
sec++;
if(sec > 59) {
sec = 0;
min++;
} else if(min > 59){
min = 0;
hour++;
}
window.setTimeout("stopWatch()", 1000);
}
stopWatch();
A list item has no .value property. Inputs or textareas have. It should be
var sec = parseInt(document.getElementById("sec").innerHTML, 10),
min = parseInt(document.getElementById("min").innerHTML, 10),
hour = parseInt(document.getElementById("hour").innerHTML, 10);
which is also parsing them into numbers.
Also, don't pass a string to setTimeout. Pass the function you want to be called:
window.setTimeout(stopWatch, 1000);
And nowhere in your code you are outputting the updated variables. They are no magic pointers to the DOM properties, but just hold numbers (or strings in your original script).
Last but not least there's a logic error in your code. You are checking whether the minutes exceed 59 only when the seconds didn't. Remove that else before the if.
1) List items LI don't have values, they have innerHTML.
var sec = document.getElementById("sec").innerHTML; (not .value)
2) Nowhere in your code do you set the contents of your LIs. JavaScript doesn't magically associate IDs with variables - you have to do that bit yourself.
Such as:
document.getElementById("hour").innerHTML = hour;
3) Never pass a timeout as a string. Use an anonymous function:
window.setTimeout(function() {stopWatch()}, 1000);
or, plainly:
window.setTimeout(stopWatch, 1000);
(function() {
var sec = document.getElementById("sec").value,
min = document.getElementById("min").value,
hour = document.getElementById("hour").value;
function stopWatch(){
sec++;
if(sec > 59) {
sec = 0;
min++;
} else if(min > 59){
min = 0;
hour++;
}
document.getElementById("sec").textContent = sec
document.getElementById("min").textContent = min
document.getElementById("hour").textContent = hour
window.setTimeout(stopWatch, 1000);
}
stopWatch();
})();
The invocation should only be
window.setInterval(stopWatch, 1000);
So to use the stopwatch, put the function inside:
var sec = 0, min = 0, hour = 0;
window.setInterval(function () {
"use strict";
sec++;
if (sec > 59) {
sec = 0;
min++;
} else if (min > 59) {
min = 0;
hour++;
}
document.getElementById("sec").innerHTML = sec;
document.getElementById("min").innerHTML = hour;
document.getElementById("hour").innerHTML = hour;
}, 1000);
Li elements has no value propertie, use innerHTML.
You could store the values for sec, min & hour in variables.
It is a nice idea to store the setTimeout() call to a variable in case you want to stop the clock later. Like "pause".
http://jsfiddle.net/chepe263/A3a9m/4/
<html>
<head>
<style type="text/css">
ul li{
float: left;
list-style-type: none !important;
}
</style>
<script type="text/javascript">//<![CDATA[
window.onload=function(){
var sec = min = hour = 0;
var clock = 0;
stopWatch = function(){
clearTimeout(clock);
sec++;
if (sec >=59){
sec = 0;
min++;
}
if (min>=59){
min=0;
hour++;
}
document.getElementById("sec").innerHTML = (sec < 10) ? "0" + sec : sec;
document.getElementById("min").innerHTML = (min < 10) ? "0" + min : min;
document.getElementById("hour").innerHTML = (hour < 10) ? "0" + hour : hour;
clock = setTimeout("stopWatch()",1000); }
stopWatch();
pause = function(){
clearTimeout(clock);
return false;
}
play = function(){
stopWatch();
return false;
}
reset = function(){
sec = min = hour = 0;
stopWatch();
return false;
}
}//]]>
</script>
</head>
<body>
<ul>
<li id="hour">00</li>
<li>:</li>
<li id="min">00</li>
<li>:</li>
<li id="sec">49</li>
</ul>
<hr />
Pause
Continue
Reset
</body>
</html>
This is my complete code, this may help you out:
<html>
<head>
<title>Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )</title>
<script language="JavaScript" type="text/javascript">
var theResult = "";
window.onload=function() { document.getElementById('morefeature').style.display = 'none'; }
function stopwatch(text) {
var d = new Date(); var h = d.getHours(); var m = d.getMinutes(); var s = d.getSeconds(); var ms = d.getMilliseconds();
document.stopwatchclock.stpwtch.value = + h + " : " + m + " : " + s + " : " + ms;
if (text == "Start") {
document.stopwatchclock.theButton.value = "Stop";
document.stopwatchclock.theButton.title = "The 'STOP' button will save the current stopwatch time in the stopwatch history, halt the stopwatch, and export the history as JSON object. A stopped stpwatch cannot be started again.";
document.getElementById('morefeature').style.display = 'block';
}
if (text == "Stop") {
var jsnResult = arrAdd();
var cnt = 0; var op= 'jeson output';
for (var i = 0; i < jsnResult.length; i++) {
if (arr[i] !== undefined) {
++cnt; /*json process*/
var j={ Record : cnt, Time : arr[i]};
var dq='"';
var json="{";
var last=Object.keys(j).length;
var count=0;
for(x in j){ json += dq+x+dq+":"+dq+j[x]+dq; count++;
if(count<last)json +=",";
}
json+="}<br>";
document.write(json);
}
}
}
if (document.stopwatchclock.theButton.value == "Start") { return true; }
SD=window.setTimeout("stopwatch();", 100);
theResult = document.stopwatchclock.stpwtch.value;
document.stopwatchclock.stpwtch.title = "Start with current time with the format (hours:mins:secs.milliseconds)" ;
}
function resetIt() {
if (document.stopwatchclock.theButton.value == "Stop") { document.stopwatchclock.theButton.value = "Start"; }
window.clearTimeout(SD);
}
function saveIt() {
var value = parseInt(document.getElementById('number').value, 10);
value = isNaN(value) ? 0 : value; value++;
document.getElementById('number').value = value;
var resultTitle = '';
if(value == '1'){ resultTitle = "<h3>History</h3><hr color='black'>"; }
var objTo = document.getElementById('stopwatchresult')
var spanTag = document.createElement("span");
spanTag.id = "span"+value;
spanTag.className ="stopWatchClass";
spanTag.title ="The stopwatch showing current stopwatch time and a history of saved times. Each saved time are shown as total duration (split time - stopwatch start time) and a lap duration (split time - previous split time). And durations are shown in this format: 'hours:mins:secs.milliseconds'";
spanTag.innerHTML = resultTitle +"<br/><b>Record " + value+" =</b> " + theResult + "";
objTo.appendChild(spanTag);
arrAdd(theResult);
return;
}
var arr = Array();
function arrAdd(value){ arr.push(value); return arr;}
</script>
<style>
center {
width: 50%;
margin-left: 25%;
}
.mainblock {
background-color: #07c1cc;
}
.stopWatchClass {
background-color: #07c1cc;
display: block;
}
#stopwatchclock input {
margin-bottom: 10px;
width: 120px;
}
</style>
</head>
<body>
<center>
<div class="mainblock">
<h1><b title="Stopwatch Application ( Using JAVASCRIPT + HTML + CSS )">Stopwatch Application</b></h1>
<form name="stopwatchclock" id="stopwatchclock">
<input type="text" size="16" class="" name="stpwtch" value=" 00 : 00 : 00 : 00" title="Initially blank" />
<input type="button" name="theButton" id="start" onClick="stopwatch(this.value);" value="Start" title="The 'START' button is start the stopwatch. An already started stopwatch cannot be started again." /><br />
<div id="morefeature">
<input type="button" value="Reset" id="resetme" onClick="resetIt();reset();" title="Once you will click on 'RESET' button will entirely reset the stopwatch so that it can be started again." />
<input type="button" name="saver" id="split" value="SPLIT" onClick="saveIt();" title="The 'SPLIT' button will save the current stopwatch time in the stopwatch history. The stopwatch will continue to progress after split." />
<div>
<input type="hidden" name="number" id="number" value="0" />
</form>
</div>
<div id="stopwatchresult"></div>
</center>
</body>

javascript count down to show days?

I have this javascript countdown that will show seconds. I need to know how I can show days in the counter instead of second.
i.e. 1 day, 2 hours left.
this is the code:
<script type="text/javascript">
var MAX_COUNTER = 1000;
var counter = null;
var counter_interval = null;
function setCookie(name,value,days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
else {
expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length,c.length);
}
}
return null;
}
function deleteCookie(name) {
setCookie(name,"",-1);
}
function resetCounter() {
counter = MAX_COUNTER;
}
function stopCounter() {
window.clearInterval(counter_interval);
deleteCookie('counter');
}
function updateCounter() {
var msg = '';
if (counter > 0) {
counter -= 1;
msg = counter;
setCookie('counter', counter, 1);
}
else {
counter = MAX_COUNTER;
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg;
}
}
function startCounter() {
stopCounter();
counter_interval = window.setInterval(updateCounter, 1000);
}
function init() {
counter = getCookie('counter');
if (!counter) {
resetCounter();
}
startCounter();
}
init();
</script>
at the moment it only shows seconds and it will restart itself once it hits 0.
http://jsfiddle.net/h2DEr/1/
function updateCounter() {
var msg = '';
if (counter > 0) {
counter -= 1;
msg = convertSecondsToDays(counter);
setCookie('counter', counter, 1);
}
else {
counter = MAX_COUNTER;
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg;
}
}
Here is the function that converts seconds to days
function convertSecondsToDays(sec) {
var days, hours,rem,mins,secs;
days = parseInt(sec/(24*3600));
rem = sec - days*3600
hours = parseInt(rem/3600);
rem = rem - hours*3600;
mins = parseInt(rem/60);
secs = rem - mins*60;
return days +" days " + hours +" hours "+mins + " mins "+ secs + " seconds";
}
update: after #sanya_zol's answer and comments from David Smith
since setInterval is not supposed to run every second, you need to change your strategy a little bit. I have modified the fiddle for that as well
Set MAX_COUNTER to a value when you want it to expire.
instead of decreasing the counter by -1, check the current time, subtract it from the expiry date and display it.
EXPIRY_SECONDS = 24*60*60;
MAX_COUNTER = parseInt(new Date().getTime()/(1000)) + EXPIRY_SECONDS;
function updateCounter() {
var msg = '',curTime = parseInt(new Date().getTime()/1000);
if (curTime < MAX_COUNTER) {
msg = convertSecondsToDays(MAX_COUNTER- curTime);
setCookie('counter', MAX_COUNTER- curTime, 1);
}
else {
MAX_COUNTER = parseInt(new Date().getTime()/1000) + EXPIRY_SECONDS;
}
var el = document.getElementById('counter');
if (el) {
el.innerHTML = msg
}
}
counter_interval = window.setInterval(updateCounter, 1000);
The 1000 is value in milliseconds so how many milliseconds are there in a day?
counter_interval = window.setInterval(updateCounter, 1000*60*60*24);
addition to vdua's answer:
Your code is really badly written.
It uses setInterval which counter is not precise (moreover, it have very, very bad precision) - so your counter's second will be equal to 1.05-1.2 real seconds (difference between real time and counter will accumulate).
You should check system time (via (new Date).getTime() ) every time at lower intervals (like 100 ms) to get precise counter.

Categories