To show clock using form elements - javascript

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.

Related

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.

Javascript doesn't work as I expect

The problem is that when I put the correct hour and the incorrect minutes it always returns me: "bad" and "very nice". I don't know what is going wrong so could you help me please.
I have the following html and JS:
<!DOCTYPE html>
<html>
<body>
<script language="Javascript">
var d = new Date();
var h = d.getHours();
var h1 = document.forms["INICI"].starthour.value;
var m = d.getMinutes();
var m1 = document.forms["INICI"].startminut.value;
function myHour() {
if ( h==h1 ) {
document.write("nice"+"<br>");
} else {
document.write("bad"+"<br>");
}
}
function myMinut() {
if ( m1==m ){
document.write("very nice"+"<br>");
} else {
document.write("very bad"+"<br>")
}
}
</script>
<form name="INICI">
start hour: <input name="starhour"/> <br />
<br>
start minut: <input name="startminut"/> <br />
<input id="insert1"
onclick="myHour(); myMinut();"
type="submit"
value="Click" />
</form>
</body>
</html>
(I'm new here.... sorry if I did this post very bad)
I had improved your code. here is a working version of it.
<!DOCTYPE html>
<html>
<body>
<form name="INICI">
start hour:
<input name="starthour" />
<br />
<br>
start minut:
<input name="startminut" />
<br />
<input id="insert1" onclick="EvaluateResults()" type="submit" value="Click" />
</form>
<script language="Javascript">
function EvaluateResults() {
var d = new Date();
var h = d.getHours();
var h1 = document.forms["INICI"].starthour.value;
var m = d.getMinutes();
var m1 = document.forms["INICI"].startminut.value;
console.log(h + ' ' + h1);
if (h == h1) {
document.write("nice" + "<br>");
}
else {
document.write("bad" + "<br>");
}
if (m1 == m) {
document.write("very nice" + "<br>");
}
else {
document.write("very bad" + "<br>")
}
}
</script>
</body>
</html>
What went wrong with your code is that you are taking the time when the JavaScript file loaded and executed and not when the button is pressed. What i did to solve your problem is I just created a method and transferred the code that acquires the time.
You are setting your variables when the page loads so they will always be the same.
If you put them inside the functions this could be solved
var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
function myHour()
{
var h1 = document.forms["INICI"].starthour.value;
if (h==h1){
document.write("nice"+"<br>");
}
else{
document.write("bad"+"<br>");
}
}
function myMinut()
{
var m1 = document.forms["INICI"].startminut.value;
if (m1==m){
document.write("very nice"+"<br>");
}
else{
document.write("very bad"+"<br>")
}
}
You have a typo:
<input name="starhour"/>
Needed
<input name="starthour"/>
Also put your script tag to the end of the body

javaScript code working in a seperate file but not part of a bigger file

I am making a simple Goal-traking completely offline HTML5 app using localStorage.
The problem that I am facing is, that, Retrieving JSON data is working completely fine in a separate file but not when put together as a part of a bigger system.
I would have kept it in a seperate file and would have stopped worrying about it, but I can't do that because of same-origin policy.
Here is the code that's working fine as a seperate file:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
window.onload = function(){
// setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data);
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.body.appendChild(document.createTextNode(
"The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
</BODY>
</HTML>
and now here is the code that is supposed to work, as all of it's different parts are working fine, all the syntax is correct, but still it is giving absolutely no output:
<HTML>
<HEAD>
</HEAD>
<BODY>
<script type="text/javascript">
function save()
{
//Get data from the form
var goal = document.getElementById("goal").value; //Get 'goal' from form
var date2 = document.getElementById("date2").value; //Get 'duedate' from the form
var active = document.getElementById("active").value; //Get 'active' from form
//Calculating the number of days remaining
var date1 = new Date(); //Current Date and Time
var dd = date1.getDate(); //Current Date
var mm = date1.getMonth()+1; //January is 0!
var yyyy = date1.getFullYear(); //Current Year
if(dd<10){dd='0'+dd} if(mm<10){mm='0'+mm} date1 = mm+'/'+dd+'/'+yyyy; //Parsing the date to the required format
var diff = Math.floor(( Date.parse(date2) - Date.parse(date1) ) / 86400000); //Calculate no. of days remaining
if (localStorage.getItem('gcount') === null) {
localStorage.setItem('gcount', "1");
var data = '{"goals":[{"goal":"'+goal+'","duedate":"'+date2+'","noofdays":"'+diff+'","active":"'+active+'"}]}';
localStorage.setItem("goals",data);
//document.getElementById("temp").innerHTML="first";
}
else{
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
var goal = "CN"
var data = { "goal": goal, "duedate": date2, "noofdays": diff, "active": active};
goalsObj.goals.push(data);
localStorage.setItem("goals", JSON.stringify(goalsObj));
}
}
function load(){
/* // setup
var goal = "CN";
var date2 = new Date();
var diff = 0;
var active = true;http://jsfiddle.net/#save
var data = '{"goals": [{"goal":"' + goal + '","duedate":"'
+ date2 + '","noofdays":"' + diff + '","active":"'
+ active + '"}]}';
localStorage.setItem("goals",data); */
// test
var goalsStr = localStorage.getItem("goals");
var goalsObj = JSON.parse(goalsStr);
for (i=0; i<goalsObj.goals.length; i++) {
if(goal==goalsObj.goals[i].goal) {
document.getElementById("duedate").innerHTML=goalsObj.goals[i].duedate;
document.getElementById("noofdays").innerHTML=goalsObj.goals[i].noofdays;
document.getElementById("active").innerHTML=goalsObj.goals[i].active;
// document.body.appendChild(document.createTextNode("The goal is " + JSON.stringify(goalsObj.goals[i])));
}
}
}
</script>
<form name="input" onsubmit="save(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<label>Due Date: </label> <input type="date" name="date2" id="date2"></span><br>
<label>Active: </label><br>
<input type="radio" name="active" id="active" value="Future">Future <br>
<input type="radio" name="active" id="active" value="Present">Present <br> <br>
<!-- Submit button to submit the form -->
<input type="submit" value="submit">
</form>
<form name="load" onsubmit="load(); return false;">
<label>Goal: </label> <input type="text" name="goal" id="goal"><br>
<input type="submit" value="submit">
<p id="temp"></p>
<p id="temp1"></p>
<p id="temp2"></p>
<p id="temp3"></p>
<p id="temp4"></p>
<p id="temp5"></p>
<p id="temp6"></p>
<p id="temp7"></p>
<p id="temp8"></p>
<p id="duedate"></p>
<p id="noofdays"></p>
<p id="active"></p>
</BODY>
</HTML>
I am getting the error that object is not a function. I have tried all other similar questions on StackOverflow and nothing worked.
What's wrong? What should I do?
You are using the same id for multiple different elements.
Also, try using IndexedDB instead of localStorage.

How to make the current time appear in an alert box

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();
}

How can a button visible only on given month and date in javascript?

I want a button to be visible on given date and month with javascript.
Javascript:
<script type="text/javascript">
function today()
{
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var d = new Date();
var curr_hour = d.getHours();
var curr_min = d.getMinutes();
if(month==1 && day==1)
{
document.getElementById('xx').style.visibility='visible';
}
else
{
document.getElementById('xx').style.visibility='hidden';
}
}
</script>
HTML:
<input type="image" SRC="/Patankar/PNH/images/click_anim.gif" id="xx" id="return1" onClick='today();' ALT="Submit Form" style="visibility:hidden;display:none" >
I tried this code but nothing happened. Please tell me my mistake.
You have two id tags on one element:
id="xx" id="return1"
Remove one of them. From your code example, you should remove id="return1".

Categories