I need to write a function to validate the time of user input from console. The format of the time is HH:mm in 24 hours time.
function isValidTime(timeString) {
var regex_time = /^\d{2}\:\d{2}$/;
if(!regex_time.test(timeString))
{
return false;
}
var hour = timeString.getHour();
var minute = timeString.getMinutes();
if ((hour > 0 && hour <= 23) && (minute > 0 && minute <= 59)) {
return true;
}
}
This is the code I have so far. When I input 5:01, the output is invalid format. When I input 17:01, it shows
node:internal/readline/emitKeypressEvents:71
throw err;
^
TypeError: timeString.getHour is not a function
Could you please help with this function, I am reading user input with readline.
I suggest you use capture groups in the regular expression... And the match method.
Match will return null if no match at all
or an array containing the full match at position 0 followed by all capture group results.
function isValidTime(timeString) {
const regex_time = /^(\d{2})\:(\d{2})$/; // Use capture groups
const timeMatches = timeString.match(regex_time)
if(!timeMatches){
return false
}
const hour = parseInt(timeMatches[1])
const minute = parseInt(timeMatches[2])
return hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59
}
console.log(isValidTime("5:01")) // false
console.log(isValidTime("17:05")) // true
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div>
<input type="text" placeholder="MM" id="month">
<input type="text" placeholder="DD" id="date">
<input type="text" placeholder="YYYY" id="year">
<button>Check</button>
<h1>Result</h1>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="script.js"></script>
</body>
</html>
let btnCheck = document.querySelector('button');
let inputMonth = document.querySelector('#month');
let inputDate = document.querySelector('#date');
let inputYear = document.querySelector('#year');
let result = document.querySelector('h1');
btnCheck.addEventListener('click', (event) => {
let month = inputMonth.value;
let year = inputYear.value;
let date = inputDate.value;
// true in the end, so that our date string and date format should match exactly - in moment js it is called Strict Parsing
result.innerText = moment(`${month}/${date}/${year}`, 'MM/DD/YYYY', true).isValid();
});
Solution :
var today = new Date();
var date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
var hour = today.getHours (
var minutes = today.getMinutes
Another Tip :
If you Get A Another Error you can write
var today = new Date();
var parag = document.getElementById("date")
var time = today.getHours () + ":" + today.getMinutes () + ":" + today.getSeconds();
parag.innerHTML = time
Related
i am truly new with programing with javaScript so i just start to learn it, it will be good you are going to reply using a simple js code
my code does'nt stop when i press stop i want to clear the interval that i named with myTimer if i didn't put setInterval inside the function it just work directly and if there is any way to make my code more short please mentiot it.
const // my variable
myHour = document.getElementById("hours"),
myMin = document.getElementById("min"),
mySecond = document.getElementById("second"),
myMiliSecond = document.getElementById("dsecond"),
startchrono = document.getElementById("start"),
getLap = document.getElementById("lap"),
stopchrono = document.getElementById("stop"),
resetchrono = document.getElementById("reset"),
result = document.getElementById("result");
let // variable
milisecond = 0,
second = 0,
minute = 0,
hour = 0,
chronoRun = false,
round = 0;
function decoration(item) // this function is for add 0 if second or minute less than 10
{
if (String(item).length < 2) {
item = "0" + item;
}
return item;
}
function lapset() // function that create a new row in the table to save rounds
{
round++;
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
if (round <= 10) {
const // insert the row in table
tr = result.insertRow(-1);
tr.insertCell(0).innerHTML = round;
tr.insertCell(-1).innerHTML = h + ":" + m + ":" + s + ":" + ds;
} else if (round <= 11) {
tr = result.insertRow(-1);
tr.insertCell(-0).innerHTML = "-";
tr.insertCell(-1).innerHTML = "you can't add any more laps";
getLap.setAttribute("disabled", "true");
}
}
function chrono() //chrono start
{
// chrono
milisecond++;
// make sure that minute, second have to be less than 60
if (milisecond > 10) {
milisecond = 0;
second++;
}
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
myMiliSecond.innerHTML = ds;
mySecond.innerHTML = s;
myMin.innerHTML = m;
myHour.innerHTML = h;
startchrono.setAttribute("disabled", "true");
}
// function chronoStarts() {}
const myTimer = () => {
setInterval(chrono, 100);
};
const test = () => {
return clearInterval(myTimer);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="chrono">
<div id="timer">
<span id="hours" class="time">00</span>
<span class="sep">:</span>
<span id="min" class="time">00</span>
<span class="sep">:</span>
<span id="second" class="time">00</span>
<span class="sep">:</span>
<span id="dsecond" class="time">00</span>
</div>
<div id="btnarea">
<button id="start" class="btnevent">start</button>
<button id="lap" class="btnevent">lap</button>
<button id="stop" class="btnevent">stop</button>
<button id="reset" class="btnevent">reset</button>
</div>
<table id="result">
<caption>saved lap</caption>
<tbody>
<tr>
<th class="round">round</th>
<th class="laptime">time</th>
</tr>
</tbody>
</table>
</div>
<script src="newpagescript.js"></script>
</body>
</html>
and that is my html code i think every is ok with my code but if there any issue i am looking for adives
You need to get the return value of the setInterval function and then pass that value as a parameter in the clearInterval function. For example, see below:
`// function chronoStarts() {}
let intervalId = 0;
const myTimer = () => {intervalId = setInterval(chrono, 100);};
const test = () => {
clearInterval(intervalId);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);`
i'm making a basic timer, is one of my first projects, when you press a button the code should create 3 different variables that obtain the values from their respective inputs, this 3 symbolize hours, minutes and seconds.
what happens is that if you console.log any of this 3 variables you get that is undefined for some reason, if you don't have this values the entire countdown will not work.
the inputs are set to start at value = 0 in the html, so it's supposed to at least return 0, not undefined
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="title-container">
<div class="title"><h1>vamos a meditar un poco...</h1> </div>
</div>
<div class="timer-container">
<div class="screen-timer"><h2></h2></div>
<input type="number" min="0" max="60" value="0" id="hours">
<input type="number" min="0" max="60" value="0" id="minutes">
<input type="number" min="0" max="60" value="0" id="seconds">
</div>
<div class="button-container">
<button class="btn">Iniciar</button>
</div>
<script src="app.js"></script>
here is the javascript code:
let button = document.querySelector(".btn");
let title = document.querySelector(".title");
let screenTimer = document.querySelector(".screen-timer");
//quotes
let quotes = ["OM MANI PADME HUM", "OM", "BUENOS PENSAMIENTOS, BUENAS PALABRAS, BUENAS ACCIONES", "YO FLUYO COMO EL AGUA"];
//timer start button
button.addEventListener("click", function(){
//time units
let h = document.getElementById("hours").value;
let m = document.getElementById("minutes").value;
let s = document.getElementById("seconds").value;
//title changer
let index = parseInt((Math.random() * quotes.length));
title.innerHTML = `<div class="title"><h1>${quotes[index]}</h1></div>`;
//interval for the timer
let intervalId = setInterval(timer, 1000);
//timer
function timer(){
if(m > 0 && s <= 59){
s--;
} else if(m > 0 && s == 0){
m--;
s = 59;
} else if (h > 0 && m == 0 && s == 0){
h--;
m = 59;
s = 59;
}
if (h === 0 && m === 0 && s === 0){
clearInterval(intervalId)
}
}
//show the timer on the screen
screenTimer.innerHTML = `<div class="screen-timer"><h2> ${h + ":" + m + ":" + s} </h2></div>`
console.log(h);
console.log(m);
console.log(s);
console.log(h.value);
console.log(m.value);
console.log(s.value);
});
i saw other solutions where people write document.getElementById(id).onClick instead of using addEventListener("click", ...) for making the button work when its clicked on, but i think it's the same
You are accessing the values for hours, minutes, and seconds correctly here,
let h = document.getElementById("hours").value;
let m = document.getElementById("minutes").value;
let s = document.getElementById("seconds").value;
And they are giving correct results in your console logs as well,
console.log(h);
console.log(m);
console.log(s);
What you are doing wrong is then trying to access the .value property of these three variables which doesn't exist and that is why undefined is getting printed.
Use h, m, s variables for your output.
The first three console.logs yield the correct results.
console.log(h);
console.log(m);
console.log(s);
These are already the values themselves not the domnodes.
console.log(h.value);
console.log(m.value);
console.log(s.value);
When you try to access the property "value" on the values themselves the result is undefined.
I have dynamically set two date inputs to pick dates based on current date in the first input(start_date), and based on what is selected in first input for the second input(end_date). The fields seem to update just well when dates are picked, until when the next date has to be in the following year, just when date picker in end_date stops respondig to min atrribute. I am testing my work in chrome browser. Can someone show me how to go around this one? Below is my code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="toMyStylesheets"/>
<link rel="stylesheet" href="toMyStylesheets"/>
<title>MyTitle</title>
</head>
<body>
<input type="date" name="start_date" id="start_date" />
<input type="date" name="end_date" id="end_date" disabled />
</body>
</html>
And below is my JavaScript:
let startDate = document.getElementById('start_date');
let endDate = document.getElementById('end_date');
// Enable endDate if startDate is filled, as well as set minimum dates
let currentDate = new Date();
let dd = currentDate.getDate();
let mm = currentDate.getMonth()+1; // January is [0] so I added 1 to get the right month.
let yy = currentDate.getFullYear();
let today = yy+'-'+mm+'-'+dd;
$(document).ready(() => {
startDate.setAttribute("min", today);
});
startDate.oninput = () => {
if (startDate.value.length > 0) {
endDate.disabled = false;
let fullSelectedDate = new Date(startDate.value);
fullSelectedDate.setDate(fullSelectedDate.getDate() + 1); // Updating selected day to following day
let selectedDd = fullSelectedDate.getDate();
let selectedMm = fullSelectedDate.getMonth() +1;
let selectedYy = fullSelectedDate.getFullYear();
let nextDay = selectedYy+'-'+selectedMm+'-'+selectedDd;
endDate.setAttribute("min", nextDay);
} else {
endDate.disabled = true;
}
};
Try like this:
$(document).ready(() => {
let startDate = document.getElementById('start_date');
let endDate = document.getElementById('end_date');
// Enable endDate if startDate is filled, as well as set minimum dates
let currentDate = new Date();
let dd = currentDate.getDate();
let mm = currentDate.getMonth() + 1; // January is [0] so I added 1 to get the right month.
let yy = currentDate.getFullYear();
if(dd < 10) {
dd = "0" + dd.toString();
};
if(mm < 10) {
mm = "0" + mm.toString();
};
let today = yy + '-' + mm + '-' + dd;
startDate.setAttribute("min", today);
startDate.oninput = () => {
if (startDate.value.length > 0) {
endDate.disabled = false;
let fullSelectedDate = new Date(startDate.value);
fullSelectedDate.setDate(fullSelectedDate.getDate() + 1); // Updating selected day to following day
let selectedDd = fullSelectedDate.getDate();
let selectedMm = fullSelectedDate.getMonth() + 1;
let selectedYy = fullSelectedDate.getFullYear();
if(selectedDd < 10) {
selectedDd = "0" + selectedDd.toString();
};
if(selectedMm < 10) {
selectedMm = "0" + selectedMm.toString();
};
let nextDay = selectedYy + '-' + selectedMm + '-' + selectedDd;
endDate.setAttribute("min", nextDay);
} else {
endDate.disabled = true;
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="toMyStylesheets"/>
<link rel="stylesheet" href="toMyStylesheets"/>
<title>MyTitle</title>
</head>
<body>
<input type="date" name="start_date" id="start_date" />
<input type="date" name="end_date" id="end_date" disabled />
</body>
</html>
The reason the min attribute on end_date was not working was because it was not strictly in 'YYYY-MM-DD' format. For example, if you set start_date to be 2020-12-31, nextDay has a value of '2021-1-1', which gets ignored in the min attribute. In the code above, a few simple if statements are added to convert the '1' values to '01' so that nextDay becomes '2021-01-01'.
I am building a project to help kids in school learn how to read faster. I have borrowed bits of code here and there and mixed up a timer and text generator.
Now I am trying to build a function to generate a summary of the latest reading time (so that they can see progress), perhaps in the form of <ol>, I guess I need to iterate over an array, push into it and then display but none of that seems to work.
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var ampm = "";
m = checkTime(m);
if (h > 12) {
h = h - 12;
ampm = " PM";
} else if (h == 12) {
h = 12;
ampm = " AM";
} else if (h < 12) {
ampm = " AM";
} else {
ampm = "PM";
};
if (h == 0) {
h = 12;
}
document.getElementById('display').innerHTML = h + ":" + m + ampm;
var t = setTimeout(function() {
startTime()
}, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
function startDate() {
var d = new Date();
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
document.getElementById("date").innerHTML = days[d.getDay()] + " | " + [d.getMonth() + 1] + "/" + d.getDate() + "/" + d.getFullYear();
}
var quotes = ["",
"\"Dude, suckin' at something is the first step at being sorta good at something.\"<br>- Jake <small><em>(Adventure Time)</em></small>",
"\"Either I will find a way, or I will make one.\"<br> - Philip Sidney",
"\"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time.\"<br>- Thomas A. Edison",
"\"You are never too old to set another goal or to dream a new dream.\"<br>- C.S Lewis",
"\"If you can dream it, you can do it.\"<br>- Walt Disney",
"\"Never give up, for that is just the place and time that the tide will turn.\"<br>- Harriet Beecher Stowe",
"\"I know where I'm going and I know the truth, and I don't have to be what you want me to be. I'm free to be what I want.\"<br>- Muhammad Ali",
"\"If you always put limit on everything you do, physical or anything else. It will spread into your work and into your life. There are no limits. There are only plateaus, and you must not stay there, you must go beyond them.\"<br>- Bruce Lee",
];
function genQuote() {
var quote = document.getElementById("quote");
var generate = document.getElementById("gen");
generate.addEventListener("click", changeText);
quote.innerHTML = quotes[0];
function changeText() {
var searchTerm = quote.innerHTML;
var index = quotes.indexOf(searchTerm) + 1;
if (index == quotes.length) index = 0;
var result = quotes[index];
quote.innerHTML = result;
return;
}
}
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime;
timeDiff /= 1000;
var seconds = Math.round(timeDiff);
var minutes = Math.round(seconds / 60);
document.getElementById("quote").innerHTML = ("You have read for:" + " " + minutes + " minutes" + " " + seconds + " seconds");
setTimeout(function() {
location.reload();;
}, 5000);
}
function report() {
// results = [];
// times = document.getElementById("quote").innerHTML;
// for (i=0; i <= times.length; i++) {
// results.push(i);
// return results;
// }
}
<div id="display"></div>
<div id="date"></div>
<div id="quote"></div>
<div id="get"></div>
Here is the HTML in case that help:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<title>2 Cool 4 School</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<body onload="startTime(); startDate()">
<div class="container">
<div id="date"></div>
<div id="display"></div>
<div id="content">
<p id="quote">"the people who are crazy enough to think they can change the world are the ones who do." <br/>- Steve Jobs</p>
</div>
</div>
<div id="b-nav">
<ul>
<button id="genone"class="btn btn-outline-primary" onclick="start()">Start</button>
<button id="gen" onclick="genQuote()">Continue reading</button>
<button id="genthree" class="btn btn-outline-success" onclick="report()">History</button>
<button id="gentwo" class="btn btn-outline-secondary" onclick="end()">End</button>
</ul>
</div>
</body>
<script src="script.js"></script>
</html>
Right now when I click Stars the timer runs, when I click End after that I am provided "you have read for: 0 minutes 4 seconds"
I would like to get a report of this something like:
you have read for: 3 minutes 30 seconds
you have read for: 2 minutes 50 seconds
you have read for: 1 minutes 40 seconds
etc Hope that helps(sorry I didnt get the snippet thing)
the biggest problem is placing "return results;" inside your loop. which means your loop never fully executes. move that outside your loop.
secondly, your report() function is just going to return a string of numbers, [0,1,2,3,4...] which is probably not what you are looking for.
I want to disable a button for a certain period of time everyday.
For ex: Let's say, html submit button gets disabled everyday between
11:00am and 4:00 pm.
<script type="text/javascript">
function checkButton() {
var date = new Date();
var hours = date.getHours();
var minutes = date.getMinutes();
//Hide button at 11:00 AM
if(hours == 11 && minutes == 00) {
$("#btn").hide();
}
//Show button at 04:00 PM
if(hours == 16 && minutes == 00) {
$("#btn").show();
}
}
</script>
HTML submit button reference.
<body>
<input id="btn" type="submit" value="submit" onload="checkButton()">
</body>
You shouldn't check for equality but rather check for dates being between the mentioned hours using < and > operators.
To check time between 11:00am and 4:00 pm:
let min = hours*60 + minutes;
if(min > 11*60 && min < 16*60) {
$("#btn").hide();
}else {
$("#btn").show();
}
And to check this everyday, you should put the checkButton function in a loop, such as by using setInterval function. Such as: for checking every 1 minute:
setInterval(checkButton, 60000);
My solution without Jquery:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id="btn">Click me</button>
<script>
window.onload = function() {
let btn = document.getElementById('btn');
function checkButton(){
let date = new Date();
let hours = date.getHours();
let minutes = date.getMinutes();
let min = hours*60 + minutes;
if(min > 11*60 && min < 16*60) {
//$("#btn").hide();
btn.style.display = 'none';
console.log('btn hide');
}else {
//$("#btn").show();
btn.style.display = 'block';
console.log('btn show');
}
}
setInterval(checkButton, 6000);
}
</script>
</body>
</html>
You currently just check for a point in time, but your description assumes you want to have a time range to be checked. Hence, try the following:
if(hour >= 11 && < 16) { $('#btn').hide() }
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
window.addEventListener("load", function(){
var currentTime = new Date();
var hours = currentTime.getHours();
var newButton = document.getElementById("btn");
if(hours >= 11 && hours <= 18) {
newButton.style.display = "none";
}
else {
newButton.style.display = "block";
}
}, false);
</script>
</head>
<body>
<div>Test</div>
<input type="submit" id="btn">
</body>
</html>
Use Php Date function to show the button between the hours.
<?php
$hour=date('H');
if(($hour <=11) || ($hour >=16)) {?>
<script type="text/javascript">
$("#button").show();
</script>
<?php }
?>