Trigger alarm when input values equals to current time - javascript

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

Related

How can I add a date stamp to comments added

I have a simple form for readers to add comments. The comments entered are listed on the website when added. I would like to register the date the comment was entered and list that underneath the comment itself, as shown on the website. Can someone assist me with the JS code for this?
Thanks, Paul
const field = document.querySelector('textarea');
const comments = document.getElementById('comment-box');
// array to store the comments
var comments_arr = [];
if(!localStorage.commentData){localStorage.commentData = [];}
else{
comments_arr = JSON.parse(localStorage.commentData);
}
// to generate html list based on comments array
const display_comments = () => {
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
submit.onclick = function(event){
event.preventDefault();
const content = field.value;
if(content.length > 0){ // if there is content
// add the comment to the array
comments_arr.unshift(content);
localStorage.commentData = JSON.stringify(comments_arr);
// re-genrate the comment html list
display_comments();
// reset the textArea content
field.value = '';
}
}
window.addEventListener('load', display_comments);
<link href="comment.css" rel="stylesheet">
<form>
<textarea id="comment" placeholder="Your response pls." value=""></textarea>
</form>
<input id="submit" type="submit" value="add">
<h4>Responses</h4>
<div id="comment-box"></div>
<script src="comment.js"></script>
if you only want date stamp then remove the var current_time from the display_comments() function.
const display_comments = () => {
var date = new Date();
var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
var current_time = date.getHours()+":"+date.getMinutes()+":"+ date.getSeconds();
var date_time = current_date+" "+current_time;
let list = '<ul>';
comments_arr.forEach(comment => {
list += `<li>${comment} created at : ${date_time}</li>`;
})
list += '</ul>';
comments.innerHTML = list;
}
let textbox=document.getElementById("textbox")
let comments=document.getElementById("comments")
let add=()=>{
let value=textbox.value
let ul=document.getElementById("ul")
let list=document.createElement("li")
var date = new Date();
var current_date = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+ date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var date_time = current_date+" "+strTime;
list.innerHTML=`comment:${value}`+" "+`Created At:${date_time}`
ul.insertBefore(list,ul.firstElementChild)
textbox.value=""
}
<textarea id="textbox" placeholder="Your response pls." value=""></textarea>
<button id="btn" onclick="add()">Add</button>
<div id="comments">
<h4>Responses</h4>
<ul id="ul"></ul>
</div>

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>

select all checkboxes at a particular time in html or js

I am in need of having a3 checkboxes that should have a tick mark from 2 pm till 11 pm IST in javascript or HTML. This is what I tried
<html>
<body>
<center>
<span style="margin-left:50px; margin-top:0px;">
<p align="left"><font color="white"> <b> India Time: 2pm to 11pm IST </b>
</br>
<input type="checkbox" id="user1" name="user1" value="user1" > User1<br>
<input type="checkbox" id="user2" name="user2" value="user2" > User2<br>
<input type="checkbox" id="user3" name="user3" value="user3" > User3<br>
</p>
<img border="1" src="https://i.postimg.cc/VkPzvHCJ/gh.png" style=" margin-top:-129px;" >
</span>
<h3 style= "font-family: "Gotham A","Gotham B",sans-serif;>
<br> <p align="center" style=" margin-top:-30px;"> <font color="#339933"> <b>RStudio Dashboard
</h3></P>
</body>
<script>
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){dd='0'+dd}
if(mm<10){mm='0'+mm}
var today = dd+'/'+mm+'/'+yyyy;
var holidays = [];
holidays = ["01/01/2019" , "26/01/2019" , "20/02/2019" , "01/05/2019" , "27/05/2019" , "04/06/2019", "04/07/2019" , "15/08/2019" , "02/09/2019" , "10/09/2019" , "02/10/2019" , "28/11/2019" , "25/12/2019"];
//var n = str.indexOf("welcome");
if {
var startTime = '2:00 PM';
var endTime = '11:00 PM';
var curr_time = getval();
//var curr_time = '12:39 AM';
//alert(curr_time);
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
//in between these two times
//alert("Yes")
document.getElementById("sid").checked = true;
document.getElementById("anil").checked = true;
document.getElementById("vin").checked = true;
} else {
//document.getElementById("user1").checked = true;
//document.getElementById("user2").checked = true;
}
function get24Hr(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours*100+minutes;
console.log(time +" - "+hours);
return hours;
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
}
else
{
print ("hello")
}
</script>
</html>
This is what I tried. The code is working, but it seems a bit complicated. Is there any simple method?
The only requirement is to tick the checkboxes from 2 pm to 11 pm IST
Add this js function. And then add "onClick" on every Input. Also the name must be the same.
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('user');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>
<input type="checkbox" onClick="toggle(this)" id="user1" name="user" value="user1" > User1<br>
<input type="checkbox" onClick="toggle(this)" id="user2" name="user" value="user2" > User2<br>
<input type="checkbox" onClick="toggle(this)" id="user3" name="user" value="user3" > User3<br>

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

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

Javascript validation form return false not working on Safari Browser in IOS

I have written condition on checking date and if lead time is less than 4 hours, show error message and do not allow further action to happen. In Android mobile and website it is working fine.
In Iphone safari browser it doesnt show my message and doesnot return false and continues to perform next action. What is wrong with my code
function validate_form() {
var mytext = "";
document.getElementById("mytext").innerHTML = "";
if ($("#pickup_time").val().trim() !== "") {
var inputDate = new Date($("#pickup_time").val().trim());
var todaysDate = new Date();
if (inputDate.setHours(0, 0, 0, 0) == todaysDate.setHours(0, 0, 0, 0)) {
var pickup_time = $("#pickup_time").val().trim();
var pickup_min = pickup_time.substr(pickup_time.length - 2);
pickup_time = pickup_time.substr(pickup_time.length - 5);
pickup_time = pickup_time.substr(0, 2);
var date = new Date();
var hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
var minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
hours = hours + 4;
if (pickup_time === hours) {
if (pickup_min >= minutes) {
return true;
} else {
document.getElementById("mytext").innerHTML = "Minimum lead time required is 4Hrs to schedule a Car!";
return false;
}
} else if (pickup_time < hours) {
document.getElementById("mytext").innerHTML = "Minimum lead time required is 4Hrs to schedule a Car!";
return false;
}
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="success.html" method="post" class="chafviews" id="booknow" onsubmit="return validate_form(event)">
<div class="pickCont">
<input type="text" class="textField pick_datepicker" value="" name="pickup_time" id="pickup_time" placeholder="Select start date" />
<div class="fieldLable">Pickup Date and Time</div>
</div>
<div class="pickCont">
<input type="text" class="textField drop_datepicker" value="" name="dropoff_time" id="dropoff_time" placeholder="Select end date" />
<div class="fieldLable">Drop-off Date and Time</div>
</div>
<p id="mytext" style="color: red; margin-top: 50px; font-size: 13px;"></p>
<input type="submit" class="selfBook" value="Proceed" />
</form>

Categories