<--THIS IS THE TIMER I WANT --> UPDATED
Trying to get the timer to automatically hit the submit button and go to next page. There is a controller that scores the quiz so I need to use the #using htmlBeginForm used below. TIMER
<div class="row">
<div class="col-md-offset-1">
<section id="questionForm">
<h2>Questions</h2>
<form name="counter">
<input type="text" size="8"
name="d2">
</form>
<script type="text/javascript">
var minutes = 1
var seconds = 00
document.counter.d2.value = '30:00'
function display()
{
if (seconds <= 0)
{
minutes -= 1
seconds += 59
}
if (minutes <= -1)
{
function nextQuestion() {
$("#questionform").trigger("submit");
}
$(document).ready(function () {
setTimeout(function () { nextQuestion() }, 5000);
});
}
else
seconds -= 1
document.counter.d2.value = minutes + ":" + seconds
setTimeout("display()", 1000)
}
display()
</script>
#using (Html.BeginForm("Index", "Questions", FormMethod.Post, new { #id = "questionform" }))
{
#Html.EditorFor(x => x.Questions)
<input type="submit" id="submit" class="btn btn-default" value="Submit" />
}
</section>
</div>
It seems you are trying to submit the form after a given time. For this you can use just the setTimeout function.
#using htmlBeginForm is the Razor syntax for creating form tag and at the end you will have the same old form tag in your rendered View. You can use below code to give your own ID.
#using (Html.BeginForm("actionName", "controllerName", FormMethod.Post, new { #id = "questionform" }))
Since you have added jQuery tag, I assume you can use jQuery and try following JavaScript code.
I assume your layout page has jQuery and script section as below.
#Scripts.Render("~/bundles/jquery")
#RenderSection("scripts", required: false)
</body>
</html>
Then your view should be like below.
<div class="col-md-offset-1">
<section id="questionForm">
<h2>Questions</h2>
<div id='countdown'></div>
#using (Html.BeginForm("Index", "Questions", FormMethod.Post, new { #id = "questionform" }))
{
#Html.EditorFor(x => x.Questions)
<input type="submit" id="submit" class="btn btn-default" value="Submit" />
}
</section>
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function() {
countdown('countdown');
});
function countdown(element) {
var interval;
var minutes = 1;
var seconds = 30;
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
el.innerHTML = "Time's Up!";
clearInterval(interval);
$("#questionform").trigger("submit");
return;
} else {
minutes--;
seconds = 60;
}
}
el.innerHTML = minutes + ' : ' + seconds;
seconds--;
}, 1000);
}
</script>
}
JSFiddle Example
Related
I've been trying to add a simple stopwatch to my Rails app, and I've adapted the one I found here: https://jsfiddle.net/waqasumer/agru2bdL/
The code seems to work in the console (the timer starts and stops), but I'm getting this error when using the controls and the UI is not showing the stopwatch (it's just reading zero):
Uncaught TypeError: Cannot set property 'innerHTML' of null
Any help to get this working would be appreciated. I've included my code below.
var min = 0;
var sec = 0;
var msec = 0;
var getMin = document.getElementById("min");
var getSec = document.getElementById("sec");
var getmsec = document.getElementById("msec");
var interval;
function timer() {
msec++
getmsec.innerHTML = msec;
if (msec >= 100) {
sec++;
if (sec <= 9) {
getSec.innerHTML = "0" + sec;
} else {
getSec.innerHTML = sec;
}
msec = 0;
} else if (sec >= 60) {
min++;
if (min <= 9) {
getMin.innerHTML = "0" + min;
} else {
getMin.innerHTML = min;
}
sec = 0;
}
}
function start() {
interval = setInterval(timer, 10);
var btn = document.getElementById("start");
btn.disabled = true;
}
function stop() {
clearInterval(interval);
var btn = document.getElementById("start");
btn.disabled = false;
}
function reset() {
min = "00";
sec = "00";
msec = "00";
getMin.innerHTML = min;
getSec.innerHTML = sec;
getmsec.innerHTML = msec;
clearInterval(interval);
}
function lapTimer() {
var Laps = document.getElementById('laps');
Laps.innerHTML += "<div>" + " " + getMin.innerHTML + ":" + getSec.innerHTML + ":" + getmsec.innerHTML + "</div>";
}
<h1 class="title">Stopwatch</h1>
<div class="stopwatch">
<div class="circle">
<div class="time"><span id="min">00</span>:<span id="sec">00</span>:<span id="msec">00</span></div>
</div>
<div class="controls">
<button id="start" onclick="start()" type="button"><img class="controls-img" id="playButton" src="<%= asset_path( 'play_button.png' ) %>" /></button>
<button onclick="stop()" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'pause_button.png' ) %>" /></button>
<button onclick="lapTimer()" id="lapButton" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'lap.png' ) %>" /></button>
<button onclick="reset()" type="button"><img class="controls-img" id="pauseButton" src="<%= asset_path( 'reset_button.png' ) %>" />
</button>
</div>
</div>
<br>
<div class="row" id="laps"></div>
The js code will executed, before the page is ready. You have 2 solutions. Put your js code at the end of the page or look here $(document).ready equivalent without jQuery
I got problem when want to automatically click submit form with javascript, So in this case i want to submit the button Validate Answer when the time is up, is there something wrong with my code
here is the code that i call submit button
document.getElementById('onResult').submit();
and below is the full code
<script type="text/javascript">
var upgradeTime = #Model.Duration;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
//alert("Your Test Time Has Expire...!");]
document.getElementById('onResult').submit();
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
</script>
<span id="countdown" class="timer"></span>
#using (Html.BeginForm("CollectQuiz", "Exam"))
{
#Html.HiddenFor(model => #Model.Id, new { htmlAttributes = new { #class = "form-control" } })
for (var i = 0; i < Model.Soals.Count(); i++)
{
<div class="modal-content">
<div class="modal-body">
<p>#Model.Soals[i].Id #Model.Soals[i].Question</p>
#Html.HiddenFor(model => #Model.Soals[i].Id, new { htmlAttributes = new { #class = "form-control" } })
#for (var j = 0; j < Model.Soals[i].Choices.Count(); j++)
{
<p>
#Html.RadioButtonFor(m => m.Soals[i].SelectedAnswerId, Model.Soals[i].Choices[j].Id, new { id = "Question" + i.ToString() + "Answer" + j.ToString() })
<label for="Question#(i)Answer#(j)">#Model.Soals[i].Choices[j].Id #Model.Soals[i].Choices[j].Name</label>
</p>
}
<button class="btn btn-sm text-info"><b>Kesulitan: #Model.Soals[i].Difficulty</b> </button>
</div>
</div>
}
<input id="onResult" type="submit" value="Validate Answers" />
}
i got error
Document.getElementById(...).submit is not a function
submit is a method of form elements, not form control elements - clicking a submit button simply submits the form the button belongs to.
A simple way to invoke the submit button's action from the button is to use its form property to access its form and them submit the form:
document.getElementById('onResult').form.submit();
Alternatively you could obtain a reference to the form by other means and call its submit method.
I'm not familiar with whatever kind of frontend framework you are using here but I do know that submit needs to be done on a form element <form> rather than an <input>. I think if you change this to reference the form element ID you'll be good to go.
https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit
I meet a problem like when I try to enter a number like 30, and count it down until 0, but it doesn't work.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script type="text/javascript">
function startTimer()
{
seconds = seconds - 1;
if (seconds <= 0)
{
seconds = 0;
}
else
{
seconds--;
}
var obj = document.getElementById("timer");
obj.display.value= seconds;
}
</script>
</head>
<body>
<form id="timer" action="#">
<p><input type="text" name="display" size="
20" /></p>
<p><input type="button" value="Start"
onclick="Id=setInterval('startTimer()', 100)" />
</form>
</script>
</body>
</html>
I think the problem is in if else statement, I am not sure if I make the user input correct.
Just assign 'seconds' to the current value of obj.display.value at he start of startTimer() and make sure to give the seconds input a 'number' type and a starting value.
Also use clearInterval(Id) to stop the timer once its finished..
function startTimer()
{
var obj = document.getElementById("timer");
/* make sure to tell javascript that 'seconds' is Number that
comes from the input box */
var seconds;
seconds = Number(obj.display.value);
/* Don't need this *AND* seconds-- */
// seconds = seconds - 1;
if (seconds <= 0)
{
clearInterval(Id);
seconds = 0;
}
else
{
seconds--;
}
obj.display.value = seconds;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script type="text/javascript">
</script>
</head>
<body>
<form id="timer" action="#">
<p><input type="number" name="display" size="
20" value="30" /></p>
<!-- changed the interval from 100ms to 1000ms -->
<p><input type="button" value="Start"
onclick="Id=setInterval('startTimer()', 1000)" />
</form>
</script>
</body>
</html>
You can use something like this:
modify the number to whatever you want, if you want an input control then I assume you know how to do it, if not let me know.
function myFunction() {
var inputVal = document.getElementById('myInput').value;
var seconds = inputVal, $seconds = document.querySelector('#countdown');
(function countdown() {
$seconds.textContent = seconds + ' second' + (seconds == 1 ? '' : 's')
if(seconds --> 0) setTimeout(countdown, 1000)
})();
}
<input type="text" id="myInput" placeholder="Enter number..." >
<button onclick="myFunction()">Start Counter</button>
<span id="countdown"></span>
asign seconds at the top of the code...
<script type="text/javascript">
seconds =100;
<input type="number" id="inp">
<div id="counter"></div>
<script>
let input = document.getElementById('inp')
let counter = document.getElementById('counter')
let handleInput = e => {
let num = Number(e.target.value)
let _counter = num - 1
let timer = setInterval(_ => {
if(!_counter)
clearInterval(timer)
counter.innerText = _counter
_counter--
}, 1000)
}
input.addEventListener('input', handleInput)
</script>
The above logic works for 1 - 9 (single-digit input), you can add a debounce if you want to go for double-digit or greater numbers
I'm building a Pomodoro Clock to improve my JavaScript, but I have a few issues. For starters, the increment/decrement buttons for the break do not update the time in the display. Secondly, the Session time doesn't restart after the first break period. Can anyone, please, advise me of where I went wrong?
The HTML:
<html>
<head>
<title>David Hall - Pomodoro Clock Zipline</title>
<link href="https://fonts.googleapis.com/css?family=Orbitron" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link href="main.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="container">
<h1 class="center">Pomodoro Clock</h1>
<div class="row">
<div class="center">
<div class="col-sm-6">Break Length</div>
<div class="col-sm-6">Work Length</div>
<div class="col-sm-6" id="center">
<div class="btn-group">
<button type="button" class="btn btn-success" id="decreaseBreak"><span class="glyphicon glyphicon-menu-left"></span>
<button type="button" class="btn btn-success"><span id="breakTime">5</span>
<button type="button" class="btn btn-success btn" id="increaseBreak"><span class="glyphicon glyphicon-menu-right"></span></div>
</div>
<div class="col-sm-6">
<div class="btn-group">
<button type="button" class="btn btn-success" id="decreaseWork"><span class="glyphicon glyphicon-menu-left"></span>
<button type="button" class="btn btn-success"><span id="workTime">25:00</span>
<button type="button" class="btn btn-success btn" id="increaseWork"> <span class="glyphicon glyphicon-menu-right"></span></div>
</div>
<br />
<br />
<br />
<br />
<div class="center">
<div class="boxed">
<br />
<span id="boxText">SESSION</span>
<br />
<br />
<br />
<span id="display"></span>
<br />
<span id="timerStatus"></span>
</div>
<br />
<button type="button" class="btn btn-success btn-sm" id="start">Start</button>
<button type="button" class="btn btn-success btn-sm" id="pause">Pause</button>
<button type="button" class="btn btn-success btn-sm" id="reset">Reset</button>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'> </script>
<script src='http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js'></script>
<script src="script.js"></script>
</body>
</html>
And the JavaScript:
var myInterval;
var workTime = document.getElementById("workTime").innerHTML = 25;
var breakTime = document.getElementById("breakTime").innerHTML = 5;
var remainSec = workTime * 60;
document.getElementById("display").innerHTML = workTime;
function startWork() {
document.getElementById("start").disabled = true;
timer(callback);
}
function pauseTime() {
clearInterval(myInterval);
document.getElementById("start").disabled = false;
}
function displayTime(remainingTime) {
if (remainingTime % 60 >= 10) {
document.getElementById('display').innerHTML = Math.floor(remainingTime / 60) + ':' + Math.floor(remainingTime % 60);
} else {
document.getElementById('display').innerHTML = Math.floor(remainingTime / 60) + ':' + "0" + Math.floor(remainingTime % 60);
}
}
function timer(pomodoro) {
var remainingTime = remainSec;
myInterval = setTimeout(function() {
displayTime(remainingTime);
if (remainingTime >= 0) {
remainSec--;
timer(pomodoro);
} else {
clearInterval();
pomodoro();
}
}, 1000);
}
var callback = function() {
console.log('callback');
document.getElementById('timerStatus').innerHTML = "Take a break!";
remainSec = breakTime * 60;
timer(callbackRest)
};
var callbackRest = function() {
clearInterval(myInterval);
console.log('callbackRest');
document.getElementById('timerStatus').innerHTML = "Begin";
remainSec = workTime * 60;
document.getElementById("start").disabled = false;
};
function resetTime() {
clearInterval(myInterval);
remainSec = workTime * 60;
startWork();
}
function decreaseWork() {
if (workTime >= 1) {
document.getElementById('workTime').innerHTML = --workTime;
remainSec = workTime * 60;
}
}
function decreaseBreak() {
if (breakTime >= 1) {
document.getElementById('breakTime').innerHTML = --breakTime;
}
}
function increaseWork() {
document.getElementById('workTime').innerHTML = ++workTime;
remainSec = workTime * 60;
}
function increaseBreak() {
document.getElementById('breakTime').innerHTML = ++breakTime;
}
document.getElementById('start').addEventListener('click', startWork);
document.getElementById('pause').addEventListener('click', pauseTime);
document.getElementById('reset').addEventListener('click', resetTime);
document.getElementById('decreaseWork').addEventListener('click', decreaseWork);
document.getElementById('decreaseBreak').addEventListener('click', decreaseBreak);
document.getElementById('increaseWork').addEventListener('click', increaseWork);
document.getElementById('increaseBreak').addEventListener('click', increaseBreak);
Any feedback is much appreciated!
I just added a few things.
First two flags were added to know if isPomodoroTime status and if isBreakTime status, maybe you ask why two? because I needed a initial state which is when both were false, with those flags I can incremente and display time without confusing, for that there is a new function callled changeTimeAndDisplay that is being called from all increase and decrease methods. I also put a startWork in the callback where suppose to be called when break time finish.
here is a demo - codepen.io
var myInterval;
var workTime = document.getElementById("workTime").innerHTML = 25;
var breakTime = document.getElementById("breakTime").innerHTML = 5;
var remainSec = workTime * 60;
var isPomodoroTime = false; //new
var isBreakTime = false; //new
//new function
function changeTimeAndDisplay(newTime){
remainSec = newTime * 60;
displayTime(remainSec);
}
document.getElementById("display").innerHTML = workTime;
function startWork() {
isPomodoroTime = true; //new
document.getElementById("start").disabled = true;
timer(callback);
}
function pauseTime() {
clearInterval(myInterval);
document.getElementById("start").disabled = false;
}
function displayTime(remainingTime) {
if (remainingTime % 60 >= 10) {
document.getElementById('display').innerHTML = Math.floor(remainingTime / 60) + ':' + Math.floor(remainingTime % 60);
} else {
document.getElementById('display').innerHTML = Math.floor(remainingTime / 60) + ':' + "0" + Math.floor(remainingTime % 60);
}
}
function timer(pomodoro) {
var remainingTime = remainSec;
myInterval = setTimeout(function() {
displayTime(remainingTime);
if (remainingTime >= 0) {
remainSec--;
timer(pomodoro);
} else {
clearInterval(myInterval); //new
pomodoro();
}
}, 1000);
}
var callback = function() {
isPomodoroTime = false; //new
isBreakTime = true; //new
console.log('callback');
document.getElementById('timerStatus').innerHTML = "Take a break!";
remainSec = breakTime * 60;
timer(callbackRest)
};
var callbackRest = function() {
isPomodoroTime = true; //new
isBreakTime = false; //new
clearInterval(myInterval);
console.log('callbackRest');
document.getElementById('timerStatus').innerHTML = "Begin";
remainSec = workTime * 60;
document.getElementById("start").disabled = false;
startWork(); //new
};
function resetTime() {
clearInterval(myInterval);
remainSec = workTime * 60;
startWork();
}
function decreaseWork() {
if (workTime >= 1) {
document.getElementById('workTime').innerHTML = --workTime;
if(isPomodoroTime || !isPomodoroTime && !isBreakTime){ //new if block
changeTimeAndDisplay(workTime);
}
}
}
function decreaseBreak() {
if (breakTime >= 1) {
document.getElementById('breakTime').innerHTML = --breakTime;
if(!isPomodoroTime && isBreakTime){ //new if block
changeTimeAndDisplay(breakTime);
}
}
}
function increaseWork() {
document.getElementById('workTime').innerHTML = ++workTime;
if(isPomodoroTime || !isPomodoroTime && !isBreakTime){ //new if block
changeTimeAndDisplay(workTime);
}
}
function increaseBreak() {
document.getElementById('breakTime').innerHTML = ++breakTime;
if(!isPomodoroTime && isBreakTime){ //new if block
changeTimeAndDisplay(breakTime);
}
}
document.getElementById('start').addEventListener('click', startWork);
document.getElementById('pause').addEventListener('click', pauseTime);
document.getElementById('reset').addEventListener('click', resetTime);
document.getElementById('decreaseWork').addEventListener('click', decreaseWork);
document.getElementById('decreaseBreak').addEventListener('click', decreaseBreak);
document.getElementById('increaseWork').addEventListener('click', increaseWork);
document.getElementById('increaseBreak').addEventListener('click', increaseBreak);
As advice you could simplify more your code for example make a function for document.getElementById(id).addEventListener(evnName,func);
function addAction(evnName,id,selector){
document.getElementById(id).addEventListener(evnName,func);
}
or
function addValue(id,value){
document.getElementById(id).innerHTML = value;
}
And replace all document.getElementById
regards.
I need help,
How to put Stop and Reset button in html and javascript
Here my countdown javascript and html code and also put chrome notifications with sound,
sounds loop notify me left 10 Seconds after countdown then 0 notify me in chrome notification, and also show countdown value in page title
function do_countdown() {
var start_num = document.getElementById("value").value;
var unit_var = document.getElementById("countdown_unit").value;
start_num = start_num * parseInt(unit_var);
var countdown_output = document.getElementById('countdown_div');
if (start_num > 0) {
countdown_output.innerHTML = format_as_time(start_num);
var t=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
}
return false;
}
function update_clock(countdown_div, new_value) {
var countdown_output = document.getElementById(countdown_div);
var new_value = new_value - 1;
if (new_value > 0) {
new_formatted_value = format_as_time(new_value);
countdown_output.innerHTML = new_formatted_value;
var t=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
} else {
countdown_output.innerHTML = "Time's UP!";
}
}
function format_as_time(seconds) {
var minutes = parseInt(seconds/60);
var seconds = seconds - (minutes*60);
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
var return_var = minutes+':'+seconds;
return return_var;
}
And also html
<form id="countdown_form" onSubmit="return do_countdown();">
Countdown from: <input type="text" style="width: 30px" id="value" value="10" text-align="center"/>
<select id="countdown_unit">
<option value="1">Seconds</option>
<option value="60">Minutes</option>
<option value="3600">Hours</option>
</select>
<input type="submit" value="Start" />
<!--<input type="button" value="Reset" id="reset">-->
</form>
<div id="countdown_div"> </div>
javascript
changes
1.taken window variables t1,t2 where the timers are going to be assigned
2.added a button(name:reset),which on click calls doReset function
3.added doStuff function
window.t1=null;
window.t2=null;
function do_countdown() {
var start_num = document.getElementById("value").value;
var unit_var = document.getElementById("countdown_unit").value;
start_num = start_num * parseInt(unit_var);
var countdown_output = document.getElementById('countdown_div');
if (start_num > 0) {
countdown_output.innerHTML = format_as_time(start_num);
window.t1=setTimeout("update_clock(\"countdown_div\", "+start_num+")", 1000);
}
return false;
}
function update_clock(countdown_div, new_value) {
var countdown_output = document.getElementById(countdown_div);
var new_value = new_value - 1;
if (new_value > 0) {
new_formatted_value = format_as_time(new_value);
countdown_output.innerHTML = new_formatted_value;
window.t2=setTimeout("update_clock(\"countdown_div\", "+new_value+")", 1000);
} else {
countdown_output.innerHTML = "Time's UP!";
}
}
function format_as_time(seconds) {
var minutes = parseInt(seconds/60);
var seconds = seconds - (minutes*60);
if (minutes < 10) {
minutes = "0"+minutes;
}
if (seconds < 10) {
seconds = "0"+seconds;
}
var return_var = minutes+':'+seconds;
return return_var;
}
function doReset(){
window.clearTimeout(window.t1);
window.clearTimeout(window.t2);
document.getElementById('countdown_div').innerHTML="";
}
HTML
<form id="countdown_form" onSubmit="return do_countdown();">
Countdown from: <input type="text" style="width: 30px" id="value" value="10" text-align="center"/>
<select id="countdown_unit">
<option value="1">Seconds</option>
<option value="60">Minutes</option>
<option value="3600">Hours</option>
</select>
<input type="submit" value="Start" />
<input type="button" onClick="return doReset();" value="Reset" id="reset">
</form>
<div id="countdown_div"> </div>
Use the reset attribute in your form to clear the form input values
<input type="reset"value="Reset">
Take a look here http://jsfiddle.net/05y89wn3/14/
you have to clear the timeout ,reset the form and change the html value of the countdown_div
var reset = document.getElementById("reset_button");
var t;
reset.onclick = function() {
clearTimeout(t);
document.getElementById("countdown_form").reset();
document.getElementById("countdown_div").innerHTML="";
}