how to submit timer value in a form when click stop? - javascript

how can i make this timer to submit form name as in name="time" and send value to $_POST['time'] when someone clicks stop and then the value i can store it into mysql database?
<div id="timer"></div>
<button type="button" onclick="stopTimer()">Stop</button>
<?php
$time = strtotime('01:00:00');
?>
<script>
var startTime = <?php echo $time;?>;
//var startTime = Date.now();
var second = 1000;
var minute = second * 60;
var hour = minute * 60;
var container = document.getElementById('timer');
function stopTimer() {
clearInterval(timer);
}
function pad(n){
return ('00' + n).slice(-2);
}
var timer = setInterval(function(){
var currentTime = Date.now();
var difference = currentTime - startTime;
var hours = pad((difference / hour) | 0);
var minutes = pad(((difference % hour) / minute) | 0);
var seconds = pad(((difference % minute) / second) | 0);
container.innerHTML = hours + ':' + minutes + ':' + seconds;
// This only represents time between renders. Actual time rendered is based
// on the elapsed time calculated above.
}, 250);
</script>
thanks for your help

As #brombeer suggested, just create a form like this:
<form action="yoururl" method="post">
<input id="timer" type="number" disabled name="time" value="<?=$time?>" /> <!--here the value is shown-->
<button type="submit">Stop</button> <!--when you click here time=xx:xx:xx is sent to yoururl-->
</form>
You can then access it from JavaScript as timer and edit it ad shown in your question

Related

how to display " backward timer " using JavaScript?

I have my DOM like this :
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
And my JavaScript Like this :
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - currentTime
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
now I want to display value in my web page But it doesn't updating. seems like its freezes. but my "setInterval()" running properly.
How can I resolve this issue? need help!
You need instead of this code
let output = value - currentTime
use this
let output = value - (currentTime * 1000)
let currentTime = 0;
let intervalClear;
let input = document.getElementById('input');
let button = document.getElementById('button')
button.addEventListener('click', ()=>{
let value = input.value * 60000;
function getTime(){
currentTime++
function backcount(currentTime){
let output = value - (currentTime * 1000)
console.log(output);
const mint = document.getElementById('mint'),
sec = document.getElementById('sec');
let minute = Math.floor(output/60000)
let second = ((output % 60000) / 1000).toFixed(0)
mint.innerText = minute;
sec.innerText = second;
if(output == 0){
clearInterval(intervalClear)
}
}
backcount(currentTime);
}
getTime()
intervalClear = setInterval(getTime, 1000)
})
const reset = document.getElementById('reset')
reset.addEventListener('click', ()=>{
clearInterval(intervalClear);
input.value = '';
})
<input type="number" id="input" value="" placeholder="Enter time in minutes">
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint"></div>
<div class="sec" id="sec"></div>
</div>
Based on #Oleg Barabanov's answer I found one bug. If you didn't enter any value in text box or first added value then click on "Reset" and click on "Go" button then counter started with negative value. I fixed that issue with this code.
Script
var intervalClear;
var input = document.querySelector('#input');
var mint = document.querySelector('#mint');
var sec = document.querySelector('#sec');
var go_button = document.querySelector('#button');
var reset_button = document.querySelector('#reset');
go_button?.addEventListener('click', () => {
if (input.value != '' && input.value != 0 && parseInt(input.value) != NaN) {
startTimer(input.value, mint, sec);
}
});
reset_button?.addEventListener('click', () => {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
});
function startTimer(duration, minElement, secElement) {
clearInterval(intervalClear);
var timer = duration * 60, minutes, seconds;
intervalClear = setInterval(function () {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
minElement.textContent = minutes;
secElement.textContent = seconds;
if (--timer < 0) {
timer = duration;
}
if (minutes == 0 && seconds == 0) {
clearInterval(intervalClear);
mint.textContent = '00';
sec.textContent = '00';
}
}, 1000);
}
DOM
<input type="number" id="input" placeholder="Enter time in minutes" >
<button id="button">Go</button>
<button id="reset">reset</button>
<div class="timer">
<div class="mint" id="mint">00</div>
<div class="sec" id="sec">00</div>
</div>

Trigger alarm when input values equals to current time

I want to create multiple alarm clocks and trigger any of the alarm if at any time the value of that alarm (hour and minute) equals the current time (hour and minute). I generates the alarm from user inputs, where the user input the set time (hour and minute) that they want the alarm to trigger, and any time the user input matches the current time, the alarm should be triggered.
The problem here is that, the alarm doesn't ring. The set time will pass and the alarm will refuse to ring.
Here is my code.
CSS
#ring {display:none;}
li {list-style-type: none; border: solid gray 1px; padding:10px; margin: 3px;}
HTML
<body onload="startTime()">
<div id="txt"></div> <br>
<h1 id="ring">Ring!!!!!!!!!</h1>
<input type="text" placeholder="hour" id="hour">
<input type="text" placeholder="minute" id="minute">
<button onclick="addAlarm()">Set alarm</button>
<ul id="list">
<!--Alarm clocks goes here-->
</ul>
</body>
JAVASCRIPT
function startTime(alarmHour, alarmMinute) {
var today = new Date();
var currentHour = today.getHours();
var currentMinute = today.getMinutes();
var currentSecond = today.getSeconds();
document.getElementById('txt').innerHTML =
currentHour + ":" + currentMinute + ":" + currentSecond;
var t = setTimeout(startTime, 500);
if(currentHour == alarmHour && currentMinute == alarmMinute) {
document.getElementById("ring").style.display = "block"
}
};
var list = document.getElementById("list");
var alHour = document.getElementById("hour");
var alMinute = document.getElementById("minute");
function newAlarm(hour, minute){
startTime(hour, minute)
theAlarm = `<li><span>${hour}:</span><span>${minute}</span></li>`;
var position = "afterbegin";
list.insertAdjacentHTML(position, theAlarm);
}
function addAlarm(){
var hour = parseInt(alHour.value);
var minute = parseInt(alMinute.value);
if (hour, minute) {
newAlarm(hour, minute);
alHour.value ="";
alMinute.value ="";
}
};
Um I dont get your question to much but here I fixed the code according to what you said
var alarmhour;
var alarmminute;
setInterval(function() {
var today = new Date();
var currentHour = today.getHours();
var currentMinute = today.getMinutes();
var currentSecond = today.getSeconds();
document.getElementById('txt').innerHTML =
currentHour + ":" + currentMinute + ":" + currentSecond;
if (currentHour == alarmhour && currentMinute == alarmminute) {
document.getElementById("ring").style.display = "block";
}
}, 500)
var list = document.getElementById("list");
var alHour = document.getElementById("hour");
var alMinute = document.getElementById("minute");
function newAlarm(hour, minute) {
alarmhour = hour;
alarmminute = minute;
theAlarm = `<li><span>${hour}:</span><span>${minute}</span></li>`;
var position = "afterbegin";
list.insertAdjacentHTML(position, theAlarm);
}
function addAlarm() {
var hour = parseInt(alHour.value);
var minute = parseInt(alMinute.value);
if (hour, minute) {
newAlarm(hour, minute);
alHour.value = "";
alMinute.value = "";
}
};
#ring {
display: none;
}
li {
list-style-type: none;
border: solid gray 1px;
padding: 10px;
margin: 3px;
}
<body>
<div id="txt"></div> <br>
<h1 id="ring">Ring!!!!!!!!!</h1>
<input type="text" placeholder="hour" id="hour">
<input type="text" placeholder="minute" id="minute">
<button onclick="addAlarm()">Set alarm</button>
<ul id="list">
<!--Alarm clocks goes here-->
</ul>
</body>
Click the run snippet above to see the code running

Countdown counter in Hours

I want to write code for a counter which countdown from 4 hours in hour, minute and second components (3:59:59 ... 3:59:58 ..... 0:0:1 ... 0:0:0) in which the user can increment or decrement any of those components by using +/-icons. I wrote a code but I cannot make it? How can I complete it? In my code just increase/decrease icon works.
function increment() {
hour = parseInt(document.getElementsByName("hour")[0].value);
minute = parseInt(document.getElementsByName("minute")[0].value);
second = parseInt(document.getElementsByName("second")[0].value);
if (second + 1 == 61) {
minute = minute + 1;
if (minute == 61) {
hour = hour + 1;
if (hour == 3) {
hour = 0;
}
minute = 0;
}
second = 0;
} else {
second += 1;
}
document.getElementsByName("hour")[0].value = hour.toString();
document.getElementsByName("minute")[0].value = minute.toString();
document.getElementsByName("second")[0].value = second.toString();
}
function decrement() {
hour = parseInt(document.getElementsByName("hour")[0].value);
minute = parseInt(document.getElementsByName("minute")[0].value);
second = parseInt(document.getElementsByName("second")[0].value);
if (second - 1 <= 0) {
minute -= 1;
if (minute <= 0) {
hour -= 1;
if (hour <= 0) {
hour = 2;
minute = 60;
} else {
minute = 60;
}
}
second = 60;
} else {
second -= 1;
}
document.getElementsByName("hour")[0].value = hour.toString();
document.getElementsByName("minute")[0].value = minute.toString();
document.getElementsByName("second")[0].value = second.toString();
}
<html>
<body>
<table>
<tr>
<td>Hour</td>
<td>
<input type="text" name = "hour" placeholder = "HOUR" value="0"/>
</td>
<td>Minute</td>
<td>
<input type="text" name="minute" placeholder="MINUTE" value="0"/>
</td>
<td>Second</td>
<td>
<input type="text" name="second" placeholder="SECOND" value="0"/>
</td>
</tr>
<tr>
<td><br>
<input type="button" name="+" value="+" onclick= "return increment()"/>
</td>
<td><br>
<input type="button" name="-" value="-" onclick="return decrement()"/>
</td>
</tr>
</table>
</body>
</html>
Here is how i would go about it, first of all, you had the script execute before the body which caused problems since the elements you were trying to select didn't exist yet,
also, you're trying to do everything everywhere, but if you keep state, it is much more manageable
<script>
const maxTime = 4 * 60 * 60; // 4 hours in seconds
const hours = document.querySelector("[name='hour']");
const minutes = document.querySelector("[name='minute']");
const seconds = document.querySelector("[name='second']");
let remaining = maxTime;
let counter = setInterval(decrement, 1000);
function increment() {
remaining = Math.max(maxTime, remaining + 1);
display();
}
function decrement() {
remaining = Math.max(0, remaining - 1);
display();
}
function display() {
const time = new Date(remaining * 1000).toISOString();
hours.value = time.slice(11, 13);
minutes.value = time.slice(14, 16);
seconds.value = time.slice(17, 19);
}
</script>
You can use the setInterval function
This will call your decrement function every second
setInterval(decrement, 1000)
The first parameter is the function to be executed.
The second parameter indicates the number of milliseconds before execution.

how to call submit button of action when time is up

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

can someone tell me what is wrong with this JS alarm

I'm trying to make a simple alarm to practice
I think the issue is with the time input, yet I can not detect where is the problem
last thing I tried is to slice the innerHTML string match it with if :D
is problem with interval or the matching with if I don't know
I'm still beginner, thanks in advance
var dateId = document.getElementById("date")
var timeId = document.getElementById("time")
var date = new Date();
dateId.innerHTML = date;
function myTimer() {
var d = new Date();
document.getElementById("time").innerHTML = d.toLocaleTimeString().slice(0, 8);
}
setInterval(myTimer, 1000);
document.getElementById("Stime").addEventListener("input", SetTime);
function SetTime() {
var input = this.value;
console.log(input)
return input;
}
var inputValue = SetTime();
function matchTime() {
if (inputValue === timeId.innerHTML) {
console.log("Alarm")
}
}
setInterval(matchTime, 1000);
console.log(inputValue); //it gives me undefined
<div id="date"> </div>
<div id="time"> </div>
<br>
<br>
<br>
<input id="Stime" type="time" step="1" name="appt-time" value="13:30">
<div id="SLtime"> </div>
<div id="SPtime"> </div>
The first time you run SetTime() right here:
var inputValue = SetTime();
this.value inside SetTime() is undefined, since it is being called by the window. When it is later called as an event on the <input>, it gives you the value you expect. Have the <input> call the function instead and you will get its value.
var stime = document.getElementById("Stime");
var inputValue = SetTime.call(stime);
Here's the full snippet:
var dateId = document.getElementById("date")
var timeId = document.getElementById("time")
var date = new Date();
dateId.innerHTML = date;
function myTimer() {
var d = new Date();
document.getElementById("time").innerHTML = d.toLocaleTimeString().slice(0, 8);
}
setInterval(myTimer, 1000);
document.getElementById("Stime").addEventListener("input", SetTime);
function SetTime() {
var input = this.value;
console.log(input)
return input;
}
var stime = document.getElementById("Stime");
var inputValue = SetTime.call(stime);
function matchTime() {
if (inputValue === timeId.innerHTML) {
console.log("Alarm")
}
}
setInterval(matchTime, 1000);
console.log(inputValue); //it gives me undefined
<div id="date"> </div>
<div id="time"> </div>
<br>
<br>
<br>
<input id="Stime" type="time" step="1" name="appt-time" value="13:30">
<div id="SLtime"> </div>
<div id="SPtime"> </div>
Actually, when you change the alarm value it's only got the hours and minutes from it until you changed the seconds manually. And we are comparing the timer (which contains hours, minutes and seconds) and alarm value which contains only hours and minutes that's why Alarm is not print.
I just add ":00" for the seconds in the timer and compare its with alarm value.
var dateId = document.getElementById("date")
var timeId = document.getElementById("time")
var date = new Date();
var setTime; // used for set the alerm time value.
dateId.innerHTML = date;
function myTimer() {
var d = new Date();
document.getElementById("time").innerHTML = d.toLocaleTimeString().slice(0, 8);
}
setInterval(myTimer, 1000);
document.getElementById("Stime").addEventListener("input", function (evt) {
// Add :00 in value for seconds.
setTime = this.value.length == 5 ? (this.value+':00') :this.value; // set the setTime (alarm value)
});
function matchTime() {
// check the alarm value with our timer
if (setTime=== timeId.innerHTML) {
console.log("Alarm")
}
}
setInterval(matchTime, 1000);
console.log(setTime);
<div id="date"> </div>
<div id="time"> </div>
<br>
<br>
<br>
<input id="Stime" type="time" step="1" name="appt-time" value="13:30" min="00:00:00">
<div id="SLtime"> </div>
<div id="SPtime"> </div>
Hope this will help you.

Categories