Home > Software design >  getting an error in if and else condition in javascript file the conditions are not checking properl
getting an error in if and else condition in javascript file the conditions are not checking properl

Time:08-29

I have written javascript code inside the script tag inside the body of an HTML file the code doesn't work as expected. the code does not check the condition properly please help me. the code snippets are as follows.`

<html lang="en">

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>challenge-5&6</title>
</head>

<body>
    <h1>Javascript Basic Challenge</h1>
    <h2>Challenge-5&6</h2>
    <script>
        var user = prompt("What's your Name?", "Aryan");
        var greetings = `Hello ${user} welcome to the wesite.`
        console.log(greetings);
        alert("Enter your age correctly! otherwise serious action will be taken against you");
        var age = prompt("Please Enter your age?", 18);
        if (age === 'Number') {
            if (age >= 18) {
                console.log("You are welcome as a new subscriber to our community! have a look around!");
            } else {
                alert("oops! You are under 18! plaese leave the site");
                console.log("oops! You are under 18! plaese leave the site");
            }
        } else {
            alert("you entered a wrong input! you have to enter a number!please try again.");
        }
    </script>
</body>

</html>

CodePudding user response:

The problem is in your if condition

if (age === 'Number') {
...
}

If you want to check the type of user input, Use regex or isNaN() function in JavaScript

Here is the solution with regex

var regex=/^[0-9] $/;
if (age.match(regex)) {
...
}

Using isnaN()

if (!isNaN(age)) {
...
}

CodePudding user response:

I think you want if(typeof age = "number"){//Do something}Because here you are checking if the string's value is "number", and no one would enter that for their age.

  • Related