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";
}
Related
I have made a quiz with JavaScript and want that when the timer is up, it should not let you attempt the quiz anymore and go to the last page which displays the score. The score is displayed by calling displayResult. I have one HTML file and one JS file. When I use setTimeout, even after the time is up, it doesn’t show the score. I think the function doesn’t get called. I have tried using setInterval instead of setTimeout but still it doesn't work. Can someone tell me what I am doing wrong?
Whole code here.
//timer code in quiz.js
const startingMinutes = 1
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
if (time == 0) {
clearInterval(vri);
}
setTimeout(displayResult, 1000);
}
The function gets called you can easily check this by inserting a console.log() inside the function.
When you would like to display the results on the same page then first clear the body and append your new created element on the body.
There is still a bug that your selected elements will always be empty but I just answer your question here "How you display it."
For debugging purposes I set the timer to 6 seconds instead of 60.
(function() {
var allQuestions = [{
question: "The tree sends downroots from its branches to the soil is know as:",
options: ["Oak", "Pine", "Banyan", "Palm"],
answer: 2
}, {
question: "Electric bulb filament is made of",
options: ["Copper", "Aluminum", "lead", "Tungsten"],
answer: 3
}, {
question: "Non Metal that remains liquid at room temprature is",
options: ["Phophorous", "Bromine", "Clorine", "Helium"],
answer: 1
}, {
question: "Which of the following is used in Pencils ?",
options: ["Graphite", "Silicon", "Charcoal", "Phosphorous"],
answer: 0
}, {
question: "Chemical formula of water ?",
options: ["NaA1O2", "H2O", "Al2O3", "CaSiO3"],
answer: 1
}, {
question: "The gas filled in electric bulb is ?",
options: ["Nitrogen", "Hydrogen", "Carbon Dioxide", "Oxygen"],
answer: 0
}, {
question: "Whashing soda is the comman name for",
options: ["Sodium Carbonate", "Calcium Bicarbonate", "Sodium Bicarbonate", "Calcium Carbonate"],
answer: 0
}, {
question: "Which gas is not known as green house gas ?",
options: ["Methane", "Nitrous oxide", "Carbon Dioxide", "Hydrogen"],
answer: 3
}, {
question: "The hardest substance availabe on earth is",
options: ["Gold", "Iron", "Diamond", "Platinum"],
answer: 2
}, {
question: "Used as a lubricant",
options: ["Graphite", "Silica", "Iron Oxide", "Diamond"],
answer: 0
}];
var quesCounter = 0;
var selectOptions = [];
var quizSpace = $('#quiz');
nextQuestion();
$('#next').click(function() {
chooseOption();
if (isNaN(selectOptions[quesCounter])) {
alert('Please select an option !');
} else {
quesCounter += 5;
nextQuestion();
}
});
$('#prev').click(function() {
chooseOption();
quesCounter -= 5;
nextQuestion();
});
function createElement(index) {
var element = $('<div>', {
id: 'question'
});
var header = $('<h2>Question No. ' + (index + 1) + ' :</h2>');
element.append(header);
var question = $('<p>').append(allQuestions[index].question);
element.append(question);
var radio = radioButtons(index);
element.append(radio);
var question1 = $('<p>').append(allQuestions[index + 1].question);
element.append(question1);
var radio1 = radioButtons1(index + 1);
element.append(radio1);
var question2 = $('<p>').append(allQuestions[index + 2].question);
element.append(question2);
var radio2 = radioButtons2(index + 2);
element.append(radio2);
var question3 = $('<p>').append(allQuestions[index + 3].question);
element.append(question3);
var radio3 = radioButtons3(index + 3);
element.append(radio3);
var question4 = $('<p>').append(allQuestions[index + 4].question);
element.append(question4);
var radio4 = radioButtons4(index + 4);
element.append(radio4);
return element;
}
function radioButtons(index) {
var radioItems = $('<ul>');
var item;
var input = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item = $('<li>');
input = '<input type="radio" name="answer" value=' + i + ' />';
input += allQuestions[index].options[i];
item.append(input);
radioItems.append(item);
}
return radioItems;
}
function radioButtons1(index) {
var radioItems1 = $('<ul>');
var item1;
var input1 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item1 = $('<li>');
input1 = '<input type="radio" name="answer1" value=' + i + ' />';
input1 += allQuestions[index].options[i];
item1.append(input1);
radioItems1.append(item1);
}
return radioItems1;
}
function radioButtons2(index) {
var radioItems2 = $('<ul>');
var item2;
var input2 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item2 = $('<li>');
input2 = '<input type="radio" name="answer2" value=' + i + ' />';
input2 += allQuestions[index].options[i];
item2.append(input2);
radioItems2.append(item2);
}
return radioItems2;
}
function radioButtons3(index) {
var radioItems3 = $('<ul>');
var item3;
var input3 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item3 = $('<li>');
input3 = '<input type="radio" name="answer3" value=' + i + ' />';
input3 += allQuestions[index].options[i];
item3.append(input3);
radioItems3.append(item3);
}
return radioItems3;
}
function radioButtons4(index) {
var radioItems4 = $('<ul>');
var item4;
var input4 = '';
for (var i = 0; i < allQuestions[index].options.length; i++) {
item4 = $('<li>');
input4 = '<input type="radio" name="answer4" value=' + i + ' />';
input4 += allQuestions[index].options[i];
item4.append(input4);
radioItems4.append(item4);
}
return radioItems4;
}
function chooseOption() {
selectOptions[quesCounter] = +$('input[name="answer"]:checked').val();
selectOptions[quesCounter + 1] = +$('input[name="answer1"]:checked').val();
selectOptions[quesCounter + 2] = +$('input[name="answer2"]:checked').val();
selectOptions[quesCounter + 3] = +$('input[name="answer3"]:checked').val();
selectOptions[quesCounter + 4] = +$('input[name="answer4"]:checked').val();
}
function nextQuestion() {
quizSpace.fadeOut(function() {
$('#question').remove();
if (quesCounter < allQuestions.length) {
var nextQuestion = createElement(quesCounter);
quizSpace.append(nextQuestion).fadeIn();
if (!(isNaN(selectOptions[quesCounter, quesCounter + 1, quesCounter + 2, quesCounter + 3, quesCounter + 4]))) {
$('input[value=' + selectOptions[quesCounter] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 1] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 2] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 3] + ']').prop('checked', true);
$('input[value=' + selectOptions[quesCounter + 4] + ']').prop('checked', true);
}
if (quesCounter === 1) {
$('#prev').show();
} else if (quesCounter === 0) {
$('#prev').hide();
$('#next').show();
}
} else {
var scoreRslt = displayResult();
quizSpace.append(scoreRslt).fadeIn();
$('#next').hide();
$('#prev').hide();
}
});
}
const startingMinutes = 0.1;
let time = startingMinutes * 60
const countdownEl = document.getElementById('countdown')
var vri = setInterval(upd, 1000)
function upd() {
const minutes = Math.floor(time / 60)
let seconds = time % 60
seconds = seconds < 10 ? '0' + seconds : seconds
countdownEl.innerHTML = minutes + ":" + seconds
time--
time = time < 0 ? 0 : time
console.log(time);
if (time === 0) {
clearInterval(vri);
setTimeout(displayResult, 1000);
}
}
function displayResult() {
console.log(selectOptions);
var correct = 0;
console.log(selectOptions);
for (var i = 0; i < selectOptions.length; i++) {
if (selectOptions[i] === allQuestions[i].answer) {
correct++;
}
}
document.body.innerHTML = "";
let score = document.createElement("p");
score.id = 'question';
if (correct === 0 && correct <= 5) {
let otherText = document.createTextNode("YOUR IQ SCORES LIES IN THE RANGE OF 70 and 79 WHICH IS CLASSIFIED AS BORDERLINE");
let img = document.createElement("img");
img.src = "img9b.png"
score.append(otherText)
score.append(img);
} else {
let tex = document.createTextNode("The Result is: " + correct);
score.appendChild(tex);
}
document.body.appendChild(score);
}
})();
<html>
<head>
<title>Make Quiz Website</title>
<link rel="stylesheet" href="quiz.css">
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans" rel="stylesheet">
</head>
<body>
<div id="container">
<h1>Quiz Website Using JavaScript</h1>
<br/>
<div id="quiz"></div>
<p id="countdown">30:00</p>
</h1>
<div class="button" id="next">Next</div>
<div class="button" id="prev">Prev</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.0.min.js"></script>
<script src="quiz.js"></script>
</body>
</html>
So I have the following code, As you can see in the HTML I have a div with id=clock and an input element also with id=clock, basically if i remove the div or comment it out, the input element works fine, on the html page the clock in the input element will display the time, I would prefer it to use the div element for styling purposes; however, if i comment out the input element and use the div it does not count up, I think I understand why but I cant seem to fix it. Can someone help explain how I can do this using the following code?
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
// Start-Stop Function
function startstop() {
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if (flagclock == 0) {
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
} else {
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
}
//Increment function
function counter(starttime) {
output = document.getElementById('output');
clock = document.getElementById('clock');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if (flagstop == 1) {
timediff = timediff + stoptime
}
if (flagclock == 1) {
clock.value = formattime(timediff, '');
refresh = setTimeout('counter(' + starttime + ');', 10);
} else {
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime, roundtype) {
if (roundtype == 'round') {
var ds = Math.round(rawtime / 100) + '';
} else {
var ds = Math.floor(rawtime / 100) + '';
}
var sec = Math.floor(rawtime / 1000);
var min = Math.floor(rawtime / 60000);
ds = ds.charAt(ds.length - 1);
if (min >= 60) {
startstop();
}
sec = sec - 60 * min + '';
if (sec.charAt(sec.length - 2) != '') {
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
} else {
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if (min.charAt(min.length - 2) != '') {
min = min.charAt(min.length - 2) + min.charAt(min.length - 1);
} else {
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
// reset function
function resetclock() {
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
output.value = '';
splitcounter = 0;
if (flagclock == 1) {
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
} else {
clock.value = "00:00:0";
}
}
//Split function
function splittime() {
if (flagclock == 1) {
if (splitdate != '') {
var splitold = splitdate.split(':');
var splitnow = clock.value.split(':');
var numbers = new Array();
var i = 0
for (i; i < splitold.length; i++) {
numbers[i] = new Array();
numbers[i][0] = splitold[i] * 1;
numbers[i][1] = splitnow[i] * 1;
}
if (numbers[1][1] < numbers[1][0]) {
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if (numbers[2][1] < numbers[2][0]) {
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
var mzeros = (numbers[0][1] - numbers[0][0]) < 10 ? '0' : '';
var szeros = (numbers[1][1] - numbers[1][0]) < 10 ? '0' : '';
output.value += '\t+' + mzeros + (numbers[0][1] - numbers[0][0]) + ':' + szeros + (numbers[1][1] - numbers[1][0]) + ':' + (numbers[2][1] - numbers[2][0]) + '\n';
}
splitdate = clock.value;
output.value += (++splitcounter) + '. ' + clock.value + '\n';
}
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" id='btn' value="Start" onclick="startstop()" ;>
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock()" ;>
<div id="clock" class="timerClock">00:00:00</div><br>
<!-- Clock 2 -->
<input id="clock" class="timerClock" type="text" value="00:00:0" style="text-align: center;" readonly=""><br>
<!-- Split Button -->
<input id="splitbutton" class="buttonZ" style="width: 120px; margin-right: 170px" type="button" value="Split Time" onclick="splittime();">
<!-- output for split times -->
<textarea id="output" spellcheck="false"></textarea>
You are using clock.value to set the contents of the <input> element. This will not work for <div> elements; you will need to use innerHTML instead:
clock = document.getElementById('clock'); //div#clock
// ...
clock.innerHTML = formattime(timediff, '');
have a div with id=clock and an input element also with id=clock,
This is bad. ID have to be UNIQUE. This is why when you have both present ( with same id ) the counter doesn't work. It selects just the first element with id clock which is the div.
It doesn't select the input. As you can see getElementById is singular. If you want to select both of them, add a common class and select that with getElementsByClassName(className) ( notice the plural Elements compared to Element from the ID selector ) or querySelectorAll(className) and loop through them.
I added clock-div as the id on the div
Also. div element does not have a value attribute ( unlike input ). To get or edit/manipulate the text inside a div element you should use div.innerText instead of div.value. As a side note, div can have HTML inside it (input can't) . You can access it with div.innerHTML
So basically you need to change the id of the div ( if you also want to keep the input ) and change clock.value to clock.innerText everywhere.
Another option would be to keep both input and div. And assign the value of the input to the div.innerText.
var flagclock = 0;
var flagstop = 0;
var stoptime = 0;
var splitcounter = 0;
var currenttime;
var splitdate = '';
var output;
var clock;
// Start-Stop Function
function startstop() {
var startstop = document.getElementById('startstopbutton');
var startdate = new Date();
var starttime = startdate.getTime();
if (flagclock == 0) {
startstop.value = 'Stop';
flagclock = 1;
counter(starttime);
} else {
startstop.value = 'Start';
flagclock = 0;
flagstop = 1;
splitdate = '';
}
}
//Increment function
function counter(starttime) {
output = document.getElementById('output');
// change here id
clock = document.getElementById('clock-div');
currenttime = new Date();
var timediff = currenttime.getTime() - starttime;
if (flagstop == 1) {
timediff = timediff + stoptime
}
if (flagclock == 1) {
clock.innerText = formattime(timediff, '');
refresh = setTimeout('counter(' + starttime + ');', 10);
} else {
window.clearTimeout(refresh);
stoptime = timediff;
}
}
function formattime(rawtime, roundtype) {
if (roundtype == 'round') {
var ds = Math.round(rawtime / 100) + '';
} else {
var ds = Math.floor(rawtime / 100) + '';
}
var sec = Math.floor(rawtime / 1000);
var min = Math.floor(rawtime / 60000);
ds = ds.charAt(ds.length - 1);
if (min >= 60) {
startstop();
}
sec = sec - 60 * min + '';
if (sec.charAt(sec.length - 2) != '') {
sec = sec.charAt(sec.length - 2) + sec.charAt(sec.length - 1);
} else {
sec = 0 + sec.charAt(sec.length - 1);
}
min = min + '';
if (min.charAt(min.length - 2) != '') {
min = min.charAt(min.length - 2) + min.charAt(min.length - 1);
} else {
min = 0 + min.charAt(min.length - 1);
}
return min + ':' + sec + ':' + ds;
}
// reset function
function resetclock() {
flagstop = 0;
stoptime = 0;
splitdate = '';
window.clearTimeout(refresh);
output.value = '';
splitcounter = 0;
if (flagclock == 1) {
var resetdate = new Date();
var resettime = resetdate.getTime();
counter(resettime);
} else {
clock.innerText = "00:00:0";
}
}
//Split function
function splittime() {
if (flagclock == 1) {
if (splitdate != '') {
var splitold = splitdate.split(':');
var splitnow = clock.value.split(':');
var numbers = new Array();
var i = 0
for (i; i < splitold.length; i++) {
numbers[i] = new Array();
numbers[i][0] = splitold[i] * 1;
numbers[i][1] = splitnow[i] * 1;
}
if (numbers[1][1] < numbers[1][0]) {
numbers[1][1] += 60;
numbers[0][1] -= 1;
}
if (numbers[2][1] < numbers[2][0]) {
numbers[2][1] += 10;
numbers[1][1] -= 1;
}
var mzeros = (numbers[0][1] - numbers[0][0]) < 10 ? '0' : '';
var szeros = (numbers[1][1] - numbers[1][0]) < 10 ? '0' : '';
output.value += '\t+' + mzeros + (numbers[0][1] - numbers[0][0]) + ':' + szeros + (numbers[1][1] - numbers[1][0]) + ':' + (numbers[2][1] - numbers[2][0]) + '\n';
}
splitdate = clock.innerText;
output.innerText += (++splitcounter) + '. ' + clock.value + '\n';
}
}
<input id="startstopbutton" class="buttonZ" style="width: 120px;" type="button" name="btn" id='btn' value="Start" onclick="startstop()" ;>
<input id="resetbutton" class="buttonZ" style="width: 120px;" type="button" name="btnRst1" id='btnRst1' value="Reset" onclick="resetclock()" ;>
<div id="clock-div" class="timerClock">00:00:00</div><br>
<!-- Clock 2 -->
<input id="clock" class="timerClock" type="text" value="00:00:0" style="text-align: center;" readonly=""><br>
<!-- Split Button -->
<input id="splitbutton" class="buttonZ" style="width: 120px; margin-right: 170px" type="button" value="Split Time" onclick="splittime();">
<!-- output for split times -->
<textarea id="output" spellcheck="false"></textarea>
A user inputs an amount of water they need, I need to calculate which bottles to use, either 10l bottles or 20l bottles. So if they ask for 67l, the script pops up with 3x20l and 1x10l
I have tried the following 2 solutions
var resinAm = rsize*1.1*2.5
var resTin = '';
if(resinAm<10){
resTin = 1;
} else {
resTin = resinAm/20;
resTin = Math.ceil(resTin);
}
and this
var resAm = resinAm;
var resAm10 = (resAm/10)+0.001;
var resAm20 = (resAm/20)*2;
if(resAm10>resAm20){
resTin10 = 1;
resTin20 = Math.floor(resAm/20);
} else {
resTin20 = Math.ceil(resAm/20);
}
I have also tried using modulo, but it always comes out with an extra 20l bottle, 70.5l came out as 5x20l and 1x10l
How do I fix this
Check the code at: https://jsfiddle.net/a4k2cyoy/2/
var resAm = 70.5;
var resAm20 = parseInt(resAm / 20);
var resAm10 = 0;
if(resAm % 20 > 10) {
resAm20++;
}
if(resAm % 20 <= 10 && resAm > 0) {
resAm10++;
}
alert(resAm + " will go into " + resAm20 + " x 20 bottles and " + resAm10 + " x 10 bottles");
As simple as this
var value = 67;
var tenLBottles = Math.ceil(value % 20 /10);
var twentyLBottles = (value - value%20)/20
You can do that, fill bottles array with what you want
var water = 67;
var bottles = [20, 10, 3]; // bottles in desc order
var currentBottleIndex = 0
while(water > 0 && currentBottleIndex < bottles.length) {
console.log(Math.floor(water / bottles[currentBottleIndex]) + ' bottles of ' + bottles[currentBottleIndex])
water = water % bottles[currentBottleIndex]
currentBottleIndex ++;
}
console.log('rest water', water)
This is a math quesion, put it simple,you can realize it this way:
var bottles=[20,10];
function choose_bottle(water) {
var bottle1_num,bottle2_num;
if(water<=10) {
return "1*"+bottles[1];
}
else if(water>10&&water<=20) {
return "1*"+bottles[0];
}
else {
bottle1_num = Math.floor(water/bottles[0]);
bottle2_num = Math.ceil((water -bottle1_num*bottles[0])/bottles[1]);
return bottle1_num+"*"+bottles[0]+" "+bottle2_num+"*"+bottles[1];
}
}
This should do the job:
var amount = 67;
var bottle20 = Math.floor(amount / 20);
var bottle10 = Math.ceil((amount - bottle20 * 20) / 10);
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
I found a textarea plugin on the internet and modified it a bit to suite my needs. It works the way I want to except for one minor detail.
As you can see, it expands and collapses the textarea as I type or delete characters.
Iif I press enter, it generates a comment div containing the contents I've typed in the textarea.
My question is, **how to I append a <br /> to my new_comment variable each time a user presses Shift + Enter?
/*!
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <jevin9#gmail.com> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return. Jevin O. Sewaruth
* ----------------------------------------------------------------------------
*
* Autogrow Textarea Plugin Version v2.0
* http://www.technoreply.com/autogrow-textarea-plugin-version-2-0
*
* Date: March 13, 2011
*/
jQuery.fn.autoGrow = function(){
return this.each(function(){
// Variables
var colsDefault = this.cols;
var rowsDefault = this.rows;
//Functions
var grow = function() {
growByRef(this);
}
var onFocus = function(obj) {
if ($(this).val() != 'Write a comment...') {
return;
} else {
$(this).parents(".comment_new_container").children("img").show();
//$(this).height(34);
$(this).width(745);
$(this).val('');
}
}
var onBlur = function(obj) {
if ($(this).val().length == 0) {
$(this).parents(".comment_new_container").children("img").hide();
//$(this).height(16);
$(this).width(795);
$(this).val('Write a comment...');
}
}
var growByRef = function(obj) {
var new_comment = '';
if (!obj.shiftKey && obj.keyCode == 13) {
obj.preventDefault();
new_comment += '<div class="comment_container" id="001">';
new_comment += '<i class="comment_delete"> </i>';
new_comment += '<img src="img/avatar45.png" />';
new_comment += 'Mickey Mouse';
new_comment += '<br/>';
new_comment += '<div class="comment_content">' + $(this).val(); + '</div> <!-- End comment_content -->';
new_comment += '<div class="comment_timestamp">13 minutes ago</div> <!-- End comment_timestamp -->';
new_comment += '</div> <!-- End comment_container -->';
$(new_comment).insertBefore($(this).parents(".comment_new_container"));
var comment_total = parseInt($('.social_menu_right li a').children('.meta.comment_total').text(), 10) + 1;
$('.social_menu_right li a').children('.meta.comment_total').text(comment_total);
$(this).val('Write a comment...');
$(this).blur();
growByRef(this);
} else {
var linesCount = 0;
var lines = obj.value.split('\n');
for (var i=lines.length-1; i>=0; --i)
{
linesCount += Math.floor((lines[i].length / colsDefault) + 1);
}
if (linesCount >= rowsDefault) {
obj.rows = linesCount + 1;
} else {
obj.rows = rowsDefault;
}
}
}
var characterWidth = function (obj){
var characterWidth = 0;
var temp1 = 0;
var temp2 = 0;
var tempCols = obj.cols;
obj.cols = 1;
temp1 = obj.offsetWidth;
obj.cols = 2;
temp2 = obj.offsetWidth;
characterWidth = temp2 - temp1;
obj.cols = tempCols;
return characterWidth;
}
// Manipulations
$(this).css("width","auto");
$(this).css("height","auto");
$(this).css("overflow","hidden");
this.style.width = ((characterWidth(this) * this.cols) + 6) + "px";
$(this).bind("focus", onFocus);
$(this).bind("blur", onBlur);
$(this).bind("keypress", growByRef);
$(this).bind("keyup", grow);
});
};
Thank you guys.
try adding this at the top of the growByRef function :
if (obj.shiftKey && obj.keyCode == 13) {
$(this).val($(this).val() + "\n");
return;
}
check out these two links here
This case is similar to yours here