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.
Related
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>
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
I want to show clock using form element like HH MM SS but it is not working.
How can I do that?
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
var t = d.getHours();
var y=d.getMinutes();
var z=d.getSeconds();
document.getElementById("demo").innerHTML = t+":"+y+":"+z;
}
</script>
<script>
function fun1() {
var d = new Date();
var t = d.getHours();
var y=d.getMinutes();
var z=d.getSeconds();
window.document.my.hh.value=t+;
window.document.my.mm.value=+y+;
window.document.my.ss.value=+z;
}
</script>
<form name="my">
HH
<input type="text" name="hh">
MM
<input type="text" name="mm">
SS
<input type="text" name="ss">
</form>
</body>
</html>
I expected output like
A script on this page starts this clock:
13:10:24
HH 13 MM 10 SS 24
but the actual output is
A script on this page starts this clock:
13:10:24
HH MM SS
You should change your code there:
window.document.my.hh.value=t;
window.document.my.mm.value=y;
window.document.my.ss.value=z;
This is a demo that I fixed: https://codepen.io/phuongnm153/pen/PrQvGq
Updated:
The question has a little change.
Then I add fun1(); into myTimer() function
I updated demo link
Put ID for each input tag, query each of them, and lastly fill the data you want.
For example:
<input type="text" name="hh" id="myH">
<script>
document.getElementById('myH').value('99999')
</script>
is this what you want?
<html>
<body>
<p>A script on this page starts this clock:</p>
<p id="demo"></p>
<form name="my">
HH
<input type="text" name="hh">
MM
<input type="text" name="mm">
SS
<input type="text" name="ss">
<input type="button" value="calc" onclick="fun1()">
</form>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
var t = d.getHours();
var y=d.getMinutes();
var z=d.getSeconds();
document.getElementById("demo").innerHTML = t+":"+y+":"+z;
}
function fun1()
{
var d = new Date();
var t = d.getHours();
var y=d.getMinutes();
var z=d.getSeconds();
window.document.my.hh.value=+t;
window.document.my.mm.value=+y;
window.document.my.ss.value=+z;
}
fun1()
</script>
</body>
</html>
You could quite easily achieve your target by doing this: (btw it's good practice to store a reference to your elements because getting elements from the DOM can be quite expensive)
let clockHolder = document.getElementsByName("my")[0];
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
clockHolder.children[0].value = toDoubleDigits(d.getHours());
clockHolder.children[1].value = toDoubleDigits(d.getMinutes());
clockHolder.children[2].value = toDoubleDigits(d.getSeconds());
}
function toDoubleDigits(int) {
if (int > 9) return int;
return "0" + int;
}
The toDoubleDigits function makes sure you always have 03:07:20 instead of 3:7:20.
I am facing some problems arrays in php,,
<input class="form-control" placeholder="Start Time"
value="'.date("H.i").'" type="text" name="starttime[]" id="starttime"/>
</div>
<div class="col-lg-4">
<input class="form-control" name="endtime[]" id="endtime" onchange="myfunction1()" value="00.00" type="text" placeholder="End Time">
This is my ajax code and when I change end time It must be show other text box
<input class="form-control" name="kmcost" id="exkms" type="text" placeholder="Cost">
But single entry working but second entry(array) Not woeking my javascript code is here please help me..
my javascript is here..
function myfunction1()
{
var ftime = document.getElementById("starttime").value;
var etime = document.getElementById("endtime").value;
var timeanswer = etime - ftime;
var localtottme = document.getElementById("textbox3").value;
if(timeanswer > 8)
{
var totextme = timeanswer-8;
}
var exkms = document.getElementById('exkms');
exkms.value=totextme;
}
Try this:
function myfunction1()
{
// fetch value of element as string, x2
var ftime = document.getElementById("starttime").value;
var etime = document.getElementById("endtime").value;
// fetch hour as string, then convert to integer, x2
ftime = parseInt(ftime.split(':')[0]);
etime = parseInt(etime.split(':')[0]);
// calculate hour difference, initialize remainder variable to 0
var hourDifference = etime - ftime;
var eightHourRemainder = 0;
// check if hour difference is more than 8, if so then calculate remainder variable
var localtottme = document.getElementById("textbox3").value;
if(hourDifference > 8)
{
eightHourRemainder = hourDifference - 8;
}
// set element value to remainder variable
var exkms = document.getElementById('exkms');
exkms.value=eightHourRemainder;
}
How does one make the current time appear in an alert box? I'm new to programming, so I'm completely lost. I'm coding in html5 or javascript. I've added most of my code here.
Here's my code:
<script>
function startTime(){
var today=Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
}
</script>
<div id="txt"></div>
<h1>What would you like it to say?</h1>
<p>Commmon Requests:</p>
<form action="">
<select name="requests" onchange ="checkIfOther();" id="dropDown1">
<option value="blank"> </option>
<option value="good morning sir">Good Morning Sir</option>
<option value="current time">Current Time</option>
<option value="other">Other</option>
</select>
</form>
</p>
<button onclick="mySubmit()" value>Submit</button>
<div id="other" style="display:none">
<br><br><label>Optional Request: </label><input type="text" id="otherText"/>
</div>
</body>
</html>
<script>
function checkIfOther(){
a=document.getElementById("dropDown1");
if(a.value == "other"){
document.getElementById("other").setAttribute("style","display:inline");
}
else{
document.getElementById("other").setAttribute("style","display:none");
}
}
</script>
<script type="text/javascript">
function mySubmit(){
var x=document.getElementById("dropDown1");
if(x.value == "other"){
alert("You have chosen: " + otherText.value);
}
else if(x.value == "current time"){
alert("The current time is: " + 'txt'.value); //what do I do here?
}
else{
alert("You have chosen: " + x.options[x.selectedIndex].text);
}
}
</script>
Am I doing something wrong?
First, your HTML is completely screwed. Validate it.
As for the code itself, startTime is broken. It needs new Date().
function startTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
return [ h, m, s ].join(':')
}
and to get it into an alert box you can just do:
alert(startTime());
If you want to put it in an element like <div id="txt"></div> you can do:
document.getElementById('txt').innerHTML = startTime();
You can do something like this.
...
else if(x.value == "current time"){
startTime();
alert("The current time is: " + document.getElementById('txt').innerHTML);
...
Make a function getTime that returns the current time string:
function getTime(){
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
return h+":"+m+":"+s;
}
Then use that:
…
else if(x.value == "current time"){
alert("The current time is: " + getTime());
}
…
If you still need the startTime function, you can use it there as well:
function startTime() {
document.getElementById('txt').innerHTML = getTime();
}