简体   繁体   中英

getting an error in if and else condition in javascript file the conditions are not checking properly

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>

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)) {
...
}

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.

When you take input from the user using prompt. By default, its type will be a string. So you have to manually cast it to the number.

var age = Number(prompt("Please Enter your age?", 18));

then you have to check the condition as below.

if (typeof age === 'number') {
    // your code goes here
} else {
    // else code here
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM