<!DOCTYPE html>
<html>
<body>
<form>
Birth Year:<br>
<input type="number" name="birthYear">
<br>
Current Year:<br>
<input type="number" name="currentYear">
</form>
<button onclick="calculateAge()">Calculate Age</button>
<div id="output"></div>
<script>
function calculateAge(ghF, xhF) {
var ghF = "birthYear"
var xhF = "currentYear"
return (xhF - ghF);
} {
document.getElementByID("output").innerHTML = text;
};
</script>
</body>
When I click on the button it should print out "You are x age". Where would I add that text? At the moment nothing happens when I click on the button.
getElementById
will return the DOM element havingid
as mentioned argument..value
is property ofinput
element which will give the value ofinput
Instead of returning value, you must set theinnerHTML/innerText
after doing subtraction.
Note: You must assign unique id
attributes to the element to retrieve DOM element.
function calculateAge() { var ghF = document.getElementById("birthYear").value; var xhF = document.getElementById("currentYear").value; document.getElementById("output").innerHTML = xhF - ghF; }
<form> Birth Year: <br> <input type="number" name="birthYear" id="birthYear"> <br>Current Year: <br> <input type="number" name="currentYear" id="currentYear"> </form> <button onclick="calculateAge()">Calculate Age</button> <div id="output"></div>
function calculateAge() {
var ghF = document.getElementById("birthYear").value;
var xhF = document.getElementById("currentYear").value;
document.getElementById("output").innerHTML="You are " +(xhF - ghF) + " age";
}
The function is badly formed.
This will do the trick:
function calculateAge() { var ghF = document.querySelector('[name="birthYear"]').value; var xhF = document.querySelector('[name="currentYear"]').value; document.getElementById("output").innerHTML = "You are "+(xhF - ghF)+" age"; }
<form> Birth Year: <br> <input type="number" name="birthYear"> <br> Current Year: <br> <input type="number" name="currentYear"> </form> <button onclick="calculateAge()">Calculate Age</button> <div id="output"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.