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>
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 made a script that (should) change the password daily using an array of passwords for each day, but I keep getting all sorts of errors.
<script>
</script>
<form>
<input type="text" placeholder="Username" id="text1" /><br>
<input type="password" placeholder="Password" id="text2" /><br>
<input type="button" class="button4" style="background-color:#9c9c9c" value="Login" onclick="javascript:validate()" />
</form>
<script type="text/javascript">
type = "text/javascript"
window.onload = function() {
chgDailyImg();
}
function chgDailyImg() {
var imagearray = new Array();
imagearray[0] = "9G7DcwnWafg*EtMH";
imagearray[1] = "MDe^5qHTG#P9dHBm";
imagearray[2] = "h%$u#2Nfu8FL9H+R";
imagearray[3] = "X&NB5tYdUs5u#G#z";
imagearray[4] = "k#Rc3LGsCdu4q%qZ";
imagearray[5] = "!$p!Ss5BA%#4zeAa";
imagearray[6] = "qz63!tue3WCUxJ#R";
var d = new Date(); /*** create a date object for use ***/
var i = d.getDay();
function validate() {
if (document.getElementById("text1").value == "student21" &&
document.getElementById("text2").value == imagearray[i]) {
console.log("RIGHT")
} else {
console.log("WRONG")
}
}
}
</script>
Mainly, it keeps saying that "validate" is not defined...
"<a class='gotoLine' href='#41:132'>41:132</a> Uncaught ReferenceError: validate is not defined"
OR
"<a class='gotoLine' href='#65:49'>65:49</a> Uncaught ReferenceError: imagearray is not defined"
Your function validate() has a scope within the function chgDailyImg(). Move it outside of the function fixes the problem.
<form>
<input type="text" placeholder="Username" id="text1" /><br>
<input type="password" placeholder="Password" id="text2" /><br>
<input type="button" class="button4" style="background-color:#9c9c9c" value="Login" onclick="javascript:validate()" />
</form>
<script type="text/javascript">
window.onload = function() {
chgDailyImg();
}
const imagearray = new Array();
imagearray[0] = "9G7DcwnWafg*EtMH";
imagearray[1] = "MDe^5qHTG#P9dHBm";
imagearray[2] = "h%$u#2Nfu8FL9H+R";
imagearray[3] = "X&NB5tYdUs5u#G#z";
imagearray[4] = "k#Rc3LGsCdu4q%qZ";
imagearray[5] = "!$p!Ss5BA%#4zeAa";
imagearray[6] = "qz63!tue3WCUxJ#R";
let i = 0;
function chgDailyImg() {
let d = new Date(); /*** create a date object for use ***/
i = d.getDay();
}
function validate() {
if (document.getElementById("text1").value == "student21" &&
document.getElementById("text2").value == imagearray[i]) {
console.log("RIGHT")
} else {
console.log("WRONG")
}
}
</script>
Update:
There are some problems with Scope of your variables and functions. Hope this reading will give you get a better idea.
Scope - MDN Web Docs
https://developer.mozilla.org/en-US/docs/Glossary/Scope
I have a JavaScript code which calculates the total cost of accomodation, but whenever i run it it doesn't work.
I have tried debugging the code but I can't seem to find any problems.
Can you please help me fix this code.
This is JavaScript and the HTML is below it:
function calcStayCost(pricePerNight, numberOfNights) {
return pricePerNight * numberOfNights
}
function calcDiscount(numNights, standardCost) {
var dRate;
if (numberOfNights < 5) {
dRate = 0
} else {
if (numberOfNights >= 5 && numberOfNights <= 10) {
dRate = 0.03
} else {
dRate = 0.05
}
}
return dRate;
}
function calcAmount(cost, discount) {
return cost - discount;
}
function validateInput(validNumber) {
if (validNumber > 0) {
return true;
}
else {
return false;
}
}
function processQuote() {
var pricePerNight = document.getElementById('price').value;
pricePerNight = Number(pricePerNight);
var totalNights = document.getElementById('nights').value;
totalNights = Number(totalNights);
var validPrice = validateInput(pricePerNight);
var validNights = validateInput(totalNights);
if (validPrice == true && validNights == true) {
var standardCost = calcStayCost(pricePerNight, totalNights);
var standardCostOut = document.getElementById('price').innerHTML = "The standard cost of stay is: $" + standardCost;
var discountAmount = calcDiscount(totalNights, standardCost);
var totalAmountDue = calcAmount(standardCost, discountAmount);
var discountOut = document.getElementById('discount').innerHTML = "The total discount amount is: $" + discountAmount;
var totalDueOut = document.getElementById('amount').innerHTML = "The total amount due is: $" + totalAmountDue;
}
else {
if (validPrice == false) {
var priceErrorOut = document.getElementById('priceErrorMessage').innerHTML = "The price" + pricePerNight + "you entered is invalid, please enter a value greater than $0";
}
if (validNights == false) {
var nightsErrorOut = document.getElementById('nightsErrorMessage').innerHTML = "The number of nights you entered is invalid, please enter a value of 1 or more"
}
}
}
function init() {
var btn = document.getElementById('send');
btn.onclick = processQuote;
}
End of JavaScript Code. The following is the HTML script:
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="Quote calculator" />
<meta name="keywords" content="quote, calculator, javascript, html" />
<meta name="author" content="Mario Stavreski" />
<title>Testing output</title>
<script src="w4P1.js"></script>
</head>
<body>
<header>
</header>
<article>
<h2> Accomodation Quote </h2>
<form>
<label> Price Per Night: <input type="text" id="pricePerNight" /> </label>
<label> Number of Nights <input type="text" id="noNights" /> </label>
<button type="button" id="send"> Submit </button>
</form>
<p id="price"></p>
<p id="discount"></p>
<p id="amount"></p>
<p id="priceErrorMessage"></p>
<p id="nightsErrorMessage"></p>
</article>
<footer><p>Produced by Mario Stavreski</p></footer>
</body>
</html>
You need to either call init() to actually trigger the method so that the onSubmit handler gets bound to your button or alternatively, you can bind it within the HTML like so
<form onsubmit="processQuote()">
<label> Price Per Night: <input type="text" id="pricePerNight" /> </label>
<label> Number of Nights <input type="text" id="noNights" /> </label>
<button type="submit" id="send"> Submit </button>
</form>
Note I change the button type to submit so that it submits the form when clicked
I have a function that gets the birthdate and don't print the output which is the sign according to the birthdate
I want the output to be under the send button (where id=output) currently works only with alert
another possibility is that the output will be in an input text.
Do you have any solution instead of alert as an output?
function yourSign() {
var signDate = $("input[name='birthDate']").val();
tempSignDate = signDate.split("-").join("/");
newSignDate = tempSignDate.substring(5, 10);
var AriesDateFrom = "21/03";
var AriesDateTo = "20/04";
var TaurusDateFrom = "21/04";
var TaurusDateTo = "20/05";
var Ad1 = AriesDateFrom.split("/");
var Ad2 = AriesDateTo.split("/");
var Td1 = TaurusDateFrom.split("/");
var Td2 = TaurusDateTo.split("/");
var s = newSignDate.split("/");
if (newSignDate == "") {
alert("enter birthday");
}else if (s >= Ad1 && s < Ad2) {
document.getElementById("output").innerHTML = "Aries";
}else if (s >= Td1 && s < Td2) {
document.getElementById("output").innerHTML = "Taurus";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<meta charset="utf-8" />
<!--<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous">
</script>-->
</head>
<body>
<div>
<form>
<label for=birthDate>birthdate</label><br /><input type="date" name="birthDate" id="birthDate" /><br />
<button onclick="yourSign()">send</button><br />
<label> your sign is </label><br />
<p id="output"></p>
<!--<input type="text" name="output" id="output" />-->
</form>
</div>
</body>
</html>
split() creates an array. You can not directly compare arrays as a whole.
Your arrays has two elements: day number and month number.
Day is always index 0 in your snippet.
Month is always index 1.
Try to compare your arrays in steps:
if ( s[1] >= Ad1[1] && s[0] >= Ad[0] && s[1] <= Ad2[1] && s[0] <= Ad2[0]) { [...] };
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>