I want to do my JavaScript revision but I got stuck to this question. is there a simple code of html and JavaScript to achieve the answers to these question?
I have tried a simple look of html and JavaScript. but since I am a beginner. some words in this question I may find it hard.
<!DOCTYPE html>
<html>
<script src="js/age.js" language="javascript"></script>
<script>
function myFunction() {
var msg;
if (age == 0 && age <= 2) {
msg = "Toddler";
} else if (age == 3 && age <= 11) {
msg = "Child";
} else if (age == 12 && age <= 17) {
msg = "Adolescent";
} else {
msg = "Adult";
}
document.getElementById("demo").innerHTML = msg;
}
</script>
<body> Age: <input type="text"> <button onsubmit="return myFunction()">Find Category</button> </body>
</html>
CodePudding user response:
- less than or equal is <= - the
=>
is called a fat arrow and used in the arrow function below - onclick is the event, but use an eventListener
- You do not store the age from the input field
- You do not have a demo element
Here is a better script. Please study it.
window.addEventListener("DOMContentLoaded", () => { // when the page has loaded
const findButton = document.getElementById("find");
const demo = document.getElementById("demo");
findButton.addEventListener("click", e => { // clicking the button
let msg;
let age = document.getElementById("age").value;
if (age >= 0 && age <= 2) {
msg = "Toddler";
} else if (age >= 3 && age <= 11) {
msg = "Child";
} else if (age >= 12 && age <= 17) {
msg = "Adolescent";
} else {
msg = "Adult";
}
demo.innerHTML = msg;
});
});
Age: <input type="text" id="age"> <button type="button" id="find">Find Category</button>
<span id="demo"></span>