Age Calculator in Javascript [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I have this codes, this code must be able to compute the age of the user and It must be displayed on the text box provided and the age must change if the user changed his birth-date.
but this code does not work, it doesn't display the computed age in the textbox.
<input name= "date" type="text" readonly="readonly" />
<select id="Ultra" onchange="run()">
<option value="11/15/991">1991-11-15</option>
<option value="10/23/1992">1992-10-23</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select" readonly="readonly"><br>
<script type="text/javascript">
function run() {
var birth = document.getElementById("Ultra").value;
var check = new Date();
var milliDay = 1000 * 60 * 60 * 24;
var AgeinDay = (check - birth) / milliday;
var ComputAge = Math.floor(AgeinDay / 365 );
var age = ComputAge / 365;
document.getElementById("srt").value = age;
}
</script>

Here is a look to complete Age Calculation in JavaScript:
<body onload="getAge()">
<h1 id="age" ></h1>
<script>
function calculateAge(dob) {
var now = new Date();
var dob = new Date(dob);
var year=now.getYear()-dob.getYear();
var month=now.getMonth()-dob.getMonth();
if(month<0){
month=now.getMonth()+12-dob.getMonth();
year=year-1;
}
var day=now.getDate()-dob.getDate();
if(day<0){
var monthNumber=dob.getMonth();
var fullDate=getFullDate(monthNumber);
day=now.getDate()+fullDate-dob.getDate();
month=month-1;
}
return year+" Years, "+month+" Months, "+day+" Days!";
};
function getFullDate(x){
switch(x){
case 0:
return 31;
break;
case 1:
return 28;
break;
case 2:
return 31;
break;
case 3:
return 30;
break;
case 4:
return 31;
break;
case 5:
return 30;
break;
case 6:
return 31;
break;
case 7:
return 31;
break;
case 8:
return 30;
break;
case 9:
return 31;
break;
case 10:
return 30;
break;
case 11:
return 31;
}
}
function getAge(){
x=prompt("Please Enter Your Date of Birth in format (yyyy-mm-dd): ","");
x=new Date(x);
document.getElementById("age").innerHTML="Your age is: "+calculateAge(x);
}
</script>
</body>

try this..
function run() {
var birth = new Date(document.getElementById("Ultra").value);
var curr = new Date();
var diff = curr.getTime() - birth.getTime();
document.getElementById("srt").value = Math.floor(diff / (1000 * 60 * 60 * 24 * 365.25));
}

There were three errors in your code, see the comments inline below:
The year value of first option was 991 instead of 1991, might cause you to think the calculation is wrong.
String containing date that is being assigned to birth variable has to be passed as parameter to Date() function to create a date object that can be used with the current date object below it.
Variable milliDay was declared, then you were trying to use milliday (wrong case D).
<input name= "date" type="text" readonly="readonly" />
<select id="Ultra" onchange="run()">
<option value="11/15/1991">1991-11-15</option> <!-- year value was 991 instead of 1991, might cause you to think the calculation is wrong -->
<option value="10/23/1992">1992-10-23</option>
</select><br><br>
TextBox1<br>
<input type="text" id="srt" placeholder="get value on option select" readonly="readonly"><br>
<script type="text/javascript">
function run() {
var birth = new Date(document.getElementById("Ultra").value); //string containing date has to be passed as parameter to Date() function to create a date object that can be used with the current date object below
var check = new Date();
var milliDay = 1000 * 60 * 60 * 24;
var AgeinDay = (check - birth) / milliDay; //variable here was milliday all small case, declared above as milliDay with a capital D
var ComputAge = Math.floor(AgeinDay / 365 );
var age = ComputAge / 365;
document.getElementById("srt").value = age;
}
</script>
This will return the following values assuming the first option is selected:
age: 0.057534246575342465
ComputAge: 21
Are you just trying to get the age in years, or months, days hours too?

Below is Advanced code for Age calculator in JavaScript
<h1>Age Calculator Tool</h1>
<h2>Hey Dear, What's your name? <br /><input type = "text" placeholder = "Enter Your Name" autofocus/></h2>
<div id = "disBlock">
<p id = "disBD"></p>
<p id = "display"></p>
<p id = "time"></p>
</div>
<div id = "postCredit">
<p id = "credit"></p>
<a id = "about" href="#" target="_blank">Know More About Me</a>
</div>
<form>
<label>Enter Your Date of Birth: <input
type = "date"/></label><br />
<button type = "button">Calculate</button>
<button type = "reset">Reset</button>
</form>
<script>
let display = document.getElementById("display");
let input = document.getElementsByTagName("input");
let button = document.getElementsByTagName("button");
let time = document.getElementById("time");
let disBlock = document.getElementById("disBlock");
let disBD = document.getElementById("disBD");
let creditBlock = document.getElementById("postCredit");
let credit = document.getElementById("credit");
let about = document.getElementById("about");
disBlock.style.display = "none";
creditBlock.style.display = "none";
let dob = new Date(), today = new Date(), calTime;
function samay() {
let d = new Date();
time.innerHTML = d.getHours() + " Hours, " +
d.getMinutes() + " Minutes, " + d.getSeconds() + " Seconds Old";
}
function calculate() {
disBlock.style.display = "block";
creditBlock.style.display = "block";
credit.innerHTML = "Thank You For Visiting<br>Our website website.com";
let x = input[1].value.split("-");
dob.setDate(x[2]);
dob.setMonth(x[1] - 1);
dob.setFullYear(x[0]);
let year, month, day, HBD;
day = (function() {
if(today.getDate() > dob.getDate()) {
return today.getDate() - dob.getDate() - 1;
}
else if(today.getDate() == dob.getDate()) {
return today.getDate() - dob.getDate();
}
else {
let calDate = new Date(dob.getFullYear(), dob.getMonth() + 1, 0);
return (today.getDate() + calDate.getDate()) - dob.getDate() - 1;
}
}());
month = (function() {
if(today.getMonth() >= dob.getMonth()) {
if(today.getDate() >= dob.getDate()) {
return today.getMonth() - dob.getMonth();
}
else {
if((today.getMonth() - 1) >= dob.getMonth()) {
return (today.getMonth() - 1) - dob.getMonth();
}
else {
return ((today.getMonth() - 1) + 12) - dob.getMonth();
}
}
}
else {
if(today.getDate() >= dob.getDate()) {
return (today.getMonth() + 12) - dob.getMonth();
}
else {
return ((today.getMonth() - 1) + 12) - dob.getMonth();
}
}
}());
year = (function() {
if(dob.getMonth() == today.getMonth()) {
if(dob.getDate() > today.getDate()) {
return (today.getFullYear() - 1) - dob.getFullYear();
}
else {
return today.getFullYear() - dob.getFullYear();
}
}
else {
if(dob.getMonth() > today.getMonth()) {
return (today.getFullYear() - 1) - dob.getFullYear();
}
else {
return today.getFullYear() - dob.getFullYear();
}
}
}());
HBD = (function(){
if(today.getMonth() == dob.getMonth()) {
if(today.getDate() == dob.getDate()) {
disBD.innerHTML = "OMG it's your Birthday<br>Happy Birthday To You<br>";
}
else {
disBD.innerHTML = "";
}
}
else {
disBD.innerHTML = "";
}
}());
display.innerHTML = "Hi Dear " + input[0].value + ", <br/>You are " + year + " Years, " + month +
" Months, " + day + " Days, ";
calTime = setInterval(samay, 1000);
}
button[0].onclick = calculate;//when calculate button is clicked
function reset() {
input[0].focus();
display.innerHTML = "";
time.innerHTML = null;
clearInterval(calTime);
disBlock.style.display = "none";
creditBlock.style.display = "none";
}
button[1].onclick = reset;//when the reset button is clicked
</script>
More source code from : https://www.technicalarp.com/2021/11/javascript-age-calculator-script-html-code.html

Related

return to zero after reach max value and add the remaining value javascript

sorry i am newbie here
i need some help,
this case like notice a time.
when real time passes input value, then span with id alertLabel will change.
the problem is, if input value plus with input with id Duration will exceed real minutes or hours.
this is my code example.
javascript.js
var alertLabel = document.getElementById("alertLabel");
var less = document.getElementById("lessThan").value.replace(":", "");
var late = document.getElementById("timeIn").value.replace(":", "");
var duration = parseInt(document.getElementById("Duration").value);
var outs = document.getElementById("timesOut").value.replace(":", "");
var lessInt = parseInt(less);
var lateInt = parseInt(late);
var outsInt = parseInt(outs);
var durationOut = outsInt + duration; // this will be exceed
var durationIn = lateInt + duration; // this will be exceed
function getAlert() {
let times = new Date();
let sh = times.getHours() + "";
let sm = times.getMinutes() + "";
let ss = times.getSeconds() + "";
let shLong = sh.length == 1 ? "0" + sh : sh;
let smLong = sm.length == 1 ? "0" + sm : sm;
let ssLong = ss.length == 1 ? "0" + ss : ss;
let shSm = shLong + smLong;
document.getElementById("clock").innerHTML = shLong + ":" + smLong + ":" + ssLong;
if (shSm >= outsInt && shSm < durationOut) {
alertLabel.innerHTML = "OUT!!";
} else if (shSm >= lessInt && shSm < lateInt) {
alertLabel.innerHTML = "hurry up, don't be late!!";
} else if (shSm >= lateInt && shSm < durationIn) {
alertLabel.innerHTML = "LATE!!";
} else {
if (shLong >= 21 || shLong <= 4) {
alertLabel.innerHTML = "good dream tonight !!";
} else if (shLong >= 5 && shLong <= 11) {
alertLabel.innerHTML = "spirit Morning !!";
} else if (shLong >= 12 && shLong <= 17) {
alertLabel.innerHTML = "happy Noon !!";
} else if (shLong >= 18 && shLong <= 20) {
alertLabel.innerHTML = "nice evening !!";
}
}
}
<!doctype html>
<html>
<head>
<title></title>
</head>
<body onload="getAlert();setInterval('getAlert()',1000)">
<span id="clock"></span>
<span id="alertLabel"></span>
<div></div>
<input class="" type="text" id="lessThan" value="13:45" name="lessThan"> <!-- when time to in is near -->
<input class="" type="text" id="timeIn" value="13:48" name="timeIn"> <!-- time in and get alert Late -->
<input type="text" id="timesOut" value="13:55" name="timesOut"> <!-- value time to out and get alert Out -->
<input type="text" name="Duration" id="Duration" value="5"> <!-- duration alert for id timeIn and timesOut if more than 100 is the problem, this input as minute -->
</body>
</html>
this is my last try, example in input id timeIn
var a = document.getElementById("timeIn").value.split(":");
for (var i = 0; i < duration; i++){
var b = parseInt(a[0]); // this for hours
var c = parseInt(a[1]); // this for minutes
var x = c + i;
if (x >= 60){
var n = b + 1;
x = x-60;
}
console.log(x);
}
in my last try, in log var x return to zero just once
and the question is, if input value with id duration more than 100, how looping, if each var x reach value (60) his return to zero and var c plus 1 each var x reach 60.
maybe anyone have an easier one to solve this case.
sorry if the explanation is unclear.

How to calculate time difference using jQuery

I have code for calculating time difference and it works well. I need to change the method (actually I added one more method in certain condition). The method that I added in a condition when the textbox has value Istirahat, and then I need to change the method to the time difference that I made minus one hour.
I think it will be confusing to see my explanation without the code.
Here's the code:
$(document).ready(function() {
var $time1 = $("#start");
var $time2 = $("#end");
var $diff = $("#jam_total");
function updateHours() {
var dtStart = new Date("7/20/2015 " + $time1.val());
var dtEnd = new Date("7/20/2015 " + $time2.val());
var stats1 = $("#status_check").val();
if(stats1!='ISTIRAHAT') {
var diff = ((dtEnd - dtStart)) / 1000;
} else if(stats1!='TANPA ISTIRAHAT') {
var diff = ((((dtEnd - dtStart)) / 1000) - 1);
}
var totalTime = 0;
if (diff > 60*60*12) {
totalTime = formatDate(60*60*12);
} else {
totalTime = formatDate(diff);
}
$diff.val(totalTime);
}
function formatDate(diff) {
var hours = parseInt(diff / 3600) % 24;
var minutes = parseInt(diff / 60) % 60;
var seconds = diff % 60;
return (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes);
}
$("#option2").on("change", function() {
if($time1.val() && $time2.val()) {
updateHours();
}
});
});
<input type="time" id="start" name="logintime"/>
<input type="time" id="end"name="logouttime" />
<br /><br />
<select name="option2" id="option2" onchange="Choose1(this)" style="float:left">
<option value="-">-</option>
<option value="istirahat">istirahat</option>
<option value="tanpa istirahat">tanpa istirahat</option>
</select>
<input type="text" name="status_check" size="8" readonly="readonly" id="status_check" style="text-transform:uppercase" />
<br /><br />
Total: <input type="text" id="jam_total" type="text" name="jam_total" size="18" readonly="readonly">
<br /><br />
<script>
function Choose1(data) {
document.getElementById("status_check").value = data.value;
}
</script>
Try to check the jQuery function at the code like this:
else if (stats1 != 'TANPA ISTIRAHAT') {
var diff = ((((dtEnd - dtStart)) / 1000) - 1);
}
var diff = (((dtEnd - dtStart)) / 1000) - 1) is what I mean, that code won't work perfectly like I want. What I want is like this:
Please check the code inside if var diff = ((dtEnd - dtStart)) / 1000; I want the result of this code to be minus one hour.
First of all there is one thing wrong, you need to set stats1 to UpperCase, otherwise you can't compare correct. Second thing is you are calculating time over seconds, you should minus 60*60 (3600 to minus 1 hours).
function updateHours(){
var dtStart = new Date("7/20/2015 " + $time1.val());
var dtEnd = new Date("7/20/2015 " + $time2.val());
var stats1 = $("#status_check").val().toUpperCase();
// if you don't add toUpperCase, istirahat won't be equal to ISTIRAHAT so everytime..
// first if block will be executed
if(stats1!='ISTIRAHAT'){
var diff = ((dtEnd - dtStart)) / 1000;
}
else if(stats1!='TANPA ISTIRAHAT'){
var diff = ((((dtEnd - dtStart)) / 1000) - 3600); // and you should minus 3600
}
var totalTime = 0;
if (diff > 60*60*12) {
totalTime = formatDate(60*60*12);
;
} else {
totalTime = formatDate(diff);
}
$diff.val(totalTime);
}
Here is the working fiddle
Hope helps,

Compare date and string with jquery

I'm trying to compare today date and the date from the string. They both has a string type. Why do I get "no!" ?
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10) ? "0" : "") + this.getDate() + "/" +(((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "/" + this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '16/10/2016';
if (String(datetodayvar) >= String(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
}
});
Turn them both to Date objects instead of strings.
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
alert("yes!");
} else {
alert("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you have your "date string" from 3 different input fields(dropdowns or whatever) don't input a string, but make the date format as follows.
var year = 2015;
var month = 2-1; // February
var day = 27;
var now = new Date(year, month, day);
That way, you don't have to worry about date notation, localisation, if you need to use a - a . or / or something else inbetween.
Also remember the month, is always -1 because it starts counting as 0(januari being 0, december being 11.
Also, keep mind of day light savings time. That might go hayward with your freshly minted date objects too by subtracting an hour.
The snippet below has all the things i'd use in a "simple" comparing mechanism.
jQuery(document).ready(function () {
var str = '';
for(var c=1;c<32;c++) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#day').html(str);
var str = '';
for(var c=0;c<12;c++) {
str += '<option value="'+c+'">'+(c+1)+'</option>';
}
$('#month').html(str);
var str = '';
for(var c=parseInt(new Date().getFullYear());c>1990;c--) {
str += '<option value="'+c+'">'+c+'</option>';
}
$('#year').html(str);
$('#istodaycheck').on('click',function() {
var day = $('#day').get(0);
var month = $('#month').get(0);
var year = $('#year').get(0);
var date = new Date(
year.options[year.selectedIndex].value,
month.options[month.selectedIndex].value,
day.options[day.selectedIndex].value);
date.correctDst();
$('#output').text(date.isToday() ? 'yes' : 'no');
});
});
/**
* Retrieve standard timezome offset
*/
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
/**
* Checks if date is in day lights savings
*/
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
/**
* corrects the unwanted substraction of an hour on fresh dates.
*/
Date.prototype.correctDst = function() {
if(!this.dst()) {
this.setHours(this.getHours()+1);
}
}
/**
* Returns a date instance without time components.
*/
Date.prototype.justDate = function() {
var date = new Date(this.getFullYear(),this.getMonth(),this.getDate());
date.correctDst();
return date;
}
/**
* Tests if given date is today.
*/
Date.prototype.isToday = function() {
// strip possible time part.
var testdate = this.justDate();
var datetodayvar = new Date().justDate();
return datetodayvar.getTime() == testdate.getTime()
}
#output {
background-color: #eee;
border: 1px solid pink;
display: block;
width: 100%;
height:200px;
text-align: center;
font-size:121pt;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="day">
</select>
<select id="month">
</select>
<select id="year">
</select>
<button id="istodaycheck">Is this date today?</button>
<div id="output">
</div>
When comparing dates, always work with Date objects. The caveat with this is that when creating the objects, the provided date strings have to be in d/m/y or d-m-y format. Also note that today is not 16/10/2016.
jQuery(document).ready(function() {
var datetodayvar = new Date();
var deadlinadate = new Date('2/11/2016');
if (datetodayvar >= deadlinadate) {
console.log("yes!");
} else {
console.log("no!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First of all you are wrongly comparing two strings as if they were the numbers, when you do like this,
if(String(datetodayvar) >= String(deadlinadate)) { }
because if you want to compare strings you would have to
if(String(datetodayvar).equals(String(deadlinadate))){...
otherwise you compare the memory locations and not actual values.
Read more What is the difference between == vs equals() in Java?
This code will check whether the two string objects are greater than or equal to each other alphabetically, and not according to your actual requirement of date comparision. The functional code would be like this:
jQuery(document).ready(function () {
Date.prototype.today = function () {
return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
}
datetodayvar = new Date().today();
deadlinadate = '02/11/2016';
if(new Date(datetodayvar) >= new Date(deadlinadate)) {
console.log("yes!");
} else {
console.log("no!");
} });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Assuming date format as dd/mm/yyyy and that deadline >= today
var ar = '02/11/2016'.split('/').map(Number);
var valid = new Date(ar[2],ar[1]-1,ar[0]) >= new Date().setHours(0,0,0,0);
console.log(valid);

How I can interpret the correct date in Javascript when the year is of the format yy?

I have defined an input that accepts only dates in HTML.
The user can enter the date manually or by using a Calendar which is defined in javascript.
I am using Javascript and Jquery to convert the input to a date:
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = new Date(lStartDateText);
var lEffEndDate = new Date(lEndDateText);
My problem is that when the user enters the following date manually 1/1/50 is interpreted as 1/1/1950 but 1/1/49 is interpreted as 1/1/2049. I want it always to be interpreted as 20xx.
On the other hand the Calendar allows the user to choose a year from 2006 to 2021 in case the user wants to choose a date from it and not enter it manually.
Hope I can get some help here ??
Try this
var lStartDateText = $j("#DateStarte").val();
var lEndDateText = $j("#DateEnd").val();
var lEffStartDate = ReFormatDate(lStartDateText);
var lEffEndDate = ReFormatDate(lEndDateText);
function ReFormatDate(dateString) {
var dateParts = dateString.split("/");
if (dateParts[2].length === 2) {
dateParts[2] = "20" + dateParts[2];
}
return new Date(dateParts.join("/"));
}
use this
var lStartDateText = "1/1/50" ;
var lEndDateText = "1/1/49" ;
var res = lStartDateText.slice(4);
var starttext = lStartDateText.replace(res,"20"+res);
var res1 = lEndDateText.slice(4);
var endtext = lEndDateText.replace(res1,"20"+res1);
alert(starttext);
alert(endtext);
var lEffStartDate = new Date(starttext);
alert("start date"+lEffStartDate);
var lEffEndDate = new Date(endtext);
alert("End Date"+lEffEndDate);
If you know your getting the last 2 digits of the year (50), and you know you always want to add the first 2 digits, which are constant (20), that's a slight modification to your code:
var lStartDateText = '20' + $j("#DateStarte").val();
var lEndDateText = '20' + $j("#DateEnd").val();
Note that this is not particularly robust, e.g. if the user enters text which is not a date you might end up with a string like '20hi', but that may be outside the scope of your question and it will be parsed as an invalid date.
$('#year').on('change keyup', function() {
var y = $('#year').val();
if (y.length === 2) {
y = '20' + y
}
if (y.length === 4) {
var dateY = new Date();
dateY.setFullYear(y);
$('#result').html(dateY);
} else {
$('#result').html('No YY or YYYY date found');
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text">
<div id="result"></div>
i hope it's will be help you.
$('#year').on('change keyup', function() {
var right_date = $('#year').val();
var data = $('#year').val().split('/');
if (data[2].length == 2){
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(0,2));
$('#result').html(data[0]+'/'+data[1]+'/'+twoDigitsCurrentYear + data[2]);
}
else {
$('#result').html(right_date);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label for="year">Enter year (YY or YYYY)</label>
<input id="year" type="text" placeholder="dd/mm/yy">
<div id="result"></div>

Javascript can not change CSS color

Hi I am new to Javascript and I just wanted to make a virtual stock simulator. I just finished the main stocks, I just thought it would be cool that when the price went up the price the price would turn green, and when the price went down the price would turn red, this where I ran into my problems, the code would not run and the text would not even show. The code is below.
The full code including HTML and CSS iS on JSfiddle (only the Javascript part is below, and the color changing parts are currently commented out , but you can just uncomment it on JSfiddle.
(function () {
var Stock1 = document.getElementById("RBC");
var Stock2 = document.getElementById("TeslaM");
var Stock3 = document.getElementById("SpaceX");
var submitDay = document.getElementById("submitDay");
var AmountOf = document.getElementById("AmountOf");
Stock1.addEventListener("click", RBC, false);
Stock2.addEventListener("click", TeslaM, false);
Stock3.addEventListener("click", SpaceX, false);
submitDay.addEventListener("click", Days, false);
function Days() {
days = document.getElementById("days").value;
}
function RBC() {
$("div").empty();
var Investments = 100000;
for (day = 1; day <= days; day++) {
var difference = (Math.random() * (1.05 - 0.95) + 0.95);
var Investments = (Investments * difference).toFixed(2);
$("div").append("<p>" + day + ". " + "Your money today " + Investments + "</p>");
/*if (difference < 1) {
document.getElementsByTagName("P").style.color = "red";
} else {
document.getElementsByTagName("P").style.color = "green";
}*/
if (day - 1 === days - 1) {
AmountOf.innerHTML = "Amount of money you have: " + "$" + Investments;
}
}
}
function TeslaM() {
$("div").empty();
var Investments = 100000;
for (day = 1; day <= days; day++) {
var difference = (Math.random() * (1.2 - 0.8) + 0.8);
var Investments = (Investments * difference).toFixed(2);
$("div").append("<p>" + day + ". " + "Your money today " + Investments + "</p>");
/*if (difference < 1) {
document.getElementsByTagName("P").style.color = "red";
} else {
document.getElementsByTagName("P").style.color = "green";
}*/
if (day - 1 === days - 1) {
AmountOf.innerHTML = "Amount of money you have: " + "$" + Investments;
}
}
}
function SpaceX() {
$("div").empty();
var Investments = 100000;
for (day = 1; day <= days; day++) {
var difference = (Math.random() * (1.4 - 0.6) + 0.6);
var Investments = (Investments * difference).toFixed(2);
$("div").append("<p>" + day + ". " + "Your money today " + Investments + "</p>");
/*if (difference < 1) {
document.getElementsByTagName("P").style.color = "red";
} else {
document.getElementsByTagName("P").style.color = "green";
}*/
if (day - 1 === days - 1) {
AmountOf.innerHTML = "Amount of money you have: " + "$" + Investments;
}
}
}
})();
And please don't laugh at how bad it is, as I said I am very new to programming overall.
getElementsByTagName (note the plural of Elements) returns an HTML Collection (which is an array-like object), not a single HTML element.
You can't set its style, you have to loop over it and set the style of each HTML element inside it.
Can you try this? You had "P" in capital letters, and the p element is lowercase.
if (difference < 1) {
document.getElementsByTagName("p").style.color = "red";
} else {
document.getElementsByTagName("p").style.color = "green";
}

Categories

Resources