document.getElementById gets the element (i.e p tag) but as soon as
it writes in it the content disappears. There is no error on console but whatever is written within p tag disappears as soon as anything is written onto the p tag.
I can't find any reason for it not working also i'am not allowed to use php for accepting form inputs.
var d=new Date();
var cday=d.getDay();
var cmonth=d.getMonth();
var cyear=d.getFullYear();
var day,month,year,dage,mage,yage;
function getDOB() {
var DOB = new Date(document.getElementById("DOB").value);
year = DOB.getFullYear();
month = DOB.getMonth();
day = DOB.getDay();
}
document.getElementById("inp").onclick = function execute() {
getDOB();
yage = cyear - year;
if (cmonth >= month) {
mage = cmonth - month;
} else {
mage = 12 - (month - cmonth);
yage = yage - 1;
}
if (cday >= day) {
dage = cday - day;
} else {
mage = mage - 1
dage = 30 - (day - cday);
}
document.getElementById("output").innerHTML = "your age is " + dage + " days " + mage + " months " + yage + " years";
}
<html>
<head>
</head>
<body>
<p id="month">
</p>
<form id="form">
<!input type="text" id="day" placeholder="dd">
<! input type="text" id="day" placeholder="mm">
<!input type="text" id="day" placeholder="yyyy">
<input type="date" id="DOB">
<button id="inp">submit</button>
<br>
</form>
<p id="output"></p>
<script src="age.js"></script>
</body>
</html>
Your code contains earlier errors and could not reach the innerHTML yet.
Here's the error to start with:
Uncaught ReferenceError: cyear is not defined
You'll also have to add return false; to the end of the function to prevent the form from submitting, as stated by #thewatcheruatu.
date=new Date(); // Get current date
cyear=date.getFullYear(); // current year
cmonth=date.getMonth()+1; // current month
cday=date.getDate(); // current day
function getDOB()
{
var DOB=new Date(document.getElementById("DOB").value);
year=DOB.getFullYear();
month=DOB.getMonth();
day=DOB.getDate(); // getDate() function returns the current date
}
function execute()
{
getDOB();
yage=cyear-year;
if( cmonth>=month)
{
mage=cmonth-month;
}
else
{
mage=12-(month-cmonth);
yage=yage-1;
}
if ( cday>=day )
{
dage=cday-day;
}
else
{
mage=mage-1
dage=30-(day-cday);
}
document.getElementById("output").innerHTML="your age is "+dage+" days "+mage+" months "+yage+ " years";
}
<html>
<head>
</head>
<body>
<p id="month">
</p>
<form id="form">
<!input type="text" id="day" placeholder="dd">
<! input type="text" id="day" placeholder="mm">
<!input type="text" id="day" placeholder="yyyy">
<input type="date" id="DOB">
<button type="button" id="inp" onclick="execute()">submit</button><br>
</form>
<p id="output"></p>
<script src="age.js"></script>
</body>
</html>
Related
I want to write a javascript that will calculate age from submittal date to today and if the item is more than 5days old will change color of text to yellow and red if its more than 10days old.
<p>text<p>
<input type="date" id="date" name="date">
<input type="submit" value="Submit">
<html>
<body>
<p>Your Age Calc<p>
<form method="GET">
<input type="date" id="date" name="date">
<button type="button" id="mybutton">Submit</button>
</form>
<div id="result"></div>
<script type="application/javascript">
function showResult() {
let result = document.getElementById("result")
let date = document.getElementById("date");
if (date.value === "" ) {
result.innerHTML = "Please input a correct date, 😅!";
} else {
let birthday = new Date (`${date.value}`)
let ageDifMs = Date.now() - birthday.getTime();
let num_days = ((ageDifMs % 31536000000) % 2628000000)/86400000;
num_days > 10 ? result.style.color = "green" : result.style.color = "blue"
result.innerHTML = "😆 Your age(days), " + num_days.toFixed(1);
}
}
document.getElementById("mybutton").onclick = showResult;
</script>
</body>
</html>
I tried to calculate the Birth year's of any age, but i could not do it like this.
And i did't see any error and the calculate function is work but it doesn't output any value.I think the error is in calculation function..
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>BirthDate</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body style="background-color: #bfc5c5">
<form style="margin-top:10px">
<input type="number" name="number" style="height:30px;width: 400px;padding-left: 10px" placeholder="type your age" id="number">
<input type="button" value="find year" id="button" style="height: 35px">
<p id="year">year</p>
</form>
<script type="text/javascript">
function calculate() {
var number = document.getElementById("number").value;
if (number == "" || number == 0) {
window.alert("Please type your correct age!");
return;
}
var date = new(Date()).getFullYear()
var birthyear = number - date;
document.getElementById("year").style.display = "block";
document.getElementById("year").innerHTML = "Your Birth Year is " + birthyear;
}
document.getElementById("year").style.display = "none";
document.getElementById("button").onclick = function {
calculate();
};
</script>
</body>
</html>
You're leaving out new from the Date constructor wrapped in parenthesis:
var date = (new Date()).getFullYear();
And missing a set of parenthesis for your onClick event handler:
document.getElementById("button").onclick = function() {...}
You've two error in your code, when you fix them all goes right :
Function missing the parentheses () at :
document.getElementById("button").onclick = function {
____________________________________________________^^
Should be :
document.getElementById("button").onclick = function() {
The definition of your date has extra parentheses () in :
var date = new(Date()).getFullYear();
______________^______^
Should be :
var date = new Date().getFullYear();
Working Snippet :
function calculate() {
var number = document.getElementById("number").value;
if (number == "" || number == 0) {
window.alert("Please type your correct age!");
return;
}
var date = new Date().getFullYear()
var birthyear = number - date;
document.getElementById("year").style.display = "block";
document.getElementById("year").innerHTML = "Your Birth Year is " + birthyear;
}
document.getElementById("year").style.display = "none";
document.getElementById("button").onclick = function() {
calculate();
};
body {
background-color: #bfc5c5;
}
<form style="margin-top:10px">
<input type="number" name="number" style="height:30px;width: 400px;padding-left: 10px" placeholder="type your age" id="number">
<input type="button" value="find year" id="button" style="height: 35px">
<p id="year">year</p>
</form>
I want my user when they click on “view age” button to calculate there age from there input, but i couldn't figure it out. I got the user to view there birth year when they click on the but.
Here is my HTML Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form id="birth">
<h2>What month were you born?</h2><input name="birthMonth" type="text" size="20">
<h2>What day was you born?</h2><input name="birthday" type="text" size="20">
<h2>Your birth year?</h2> <input name="birthYear" type="text" size="20">
</form>
<button onclick="outputbirth()">Submit</button>
<button onclick="submitBday()">View Age</button>
<p id="output"></p>
<p id="age"></p>
<script type="text/javascript" src="scripts/scripts.js"></script>
</body>
</html>
JavaScript Code, function submitBday is the button on the html document:
function outputbirth() {
// Getting the form id "birth"
var x = document.getElementById("birth");
var text = "";
// Getting the users input values of Month, Day, Year.
for (i = 0; i < x.length; i++) {
text += x.elements[i].value + " ";
}
// This is going to print out the result on output id in the html document
document.getElementById("output").innerHTML = text;
}
function submitBday() {
}
You already concatenated a string from the input fields. So what you want to do to calculate the age is to construct a date object from the input fields. Just collect the input fields like you did before in a loop, but do not separate the values by an empty space but use a comma.
var bDay += x.elements[i].value + ",";
Then pass the bDay to a new date object.
var start = new Date(bDay);
Now subtract the just created date from now.
var elapsed = Date.now() - start;
This will give you the age in milliseconds. To calculate the years from milliseconds you could do this.
var age = Math.floor(((((elapsed / 1000) / 60) / 60) /24) / 365);
This will give you the age in years. If you want to find out more about the JS date object check out the moz dev network page on Date.
I left a snipped for you. Have fun.
function submitBday() {
var now = Date.now(),
x = document.getElementById("birth"),
bDay = "",
start,
elapsed,
age;
for (i = 0; i < x.length; i++) {
bDay += x.elements[i].value + ",";
}
start = new Date(bDay);
elapsed = now - start;
age = Math.floor(((((elapsed / 1000) / 60) / 60) /24) / 365);
document.getElementById("age").innerHTML = "You are " + age + " years young.";
}
<form id="birth">
<h2>What month were you born?</h2><input name="birthMonth" type="text" size="20">
<h2>What day was you born?</h2><input name="birthday" type="text" size="20">
<h2>Your birth year?</h2> <input name="birthYear" type="text" size="20">
</form>
<button onclick="submitBday()">View Age</button>
<p id="age"></p>
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
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.