Ad

JavaScript Not Randomly Selecting Names From The Specific Array List

- 1 answer

I am making a random name picker (not a generator), and when I put Alex in the textbox it should pick a random name from randomNicknames array - which it works. But when I input a name other than Alex, it still picks a random names from randomNicknames array. I want to make it pick a name from randomNicknames2 array when user inputs a name other than alex.

let realName = document.getElementById("name");

let randomNicknames = [
    "Noob",
    "Doge",
    "Roblox Bully",
    "Mama",
    "Doodle"
];

let randomNicknames2 = [
    "Ironman",
    "Howard the Alien",
    "Roblox rich kid",
    "Moto Moto",
    "Muhammad the 2nd"
];

let randomNick = randomNicknames[Math.floor(Math.random() * randomNicknames.length)];
let randomNick2 = randomNicknames2[Math.floor(Math.random() * randomNicknames2.length)];

function generate() {
    if (realName == "Alex" || "alex" || "Alexander" || "alexander") {
    document.getElementById("demo").innerHTML = randomNick;
    } else {
        document.getElementById("demo").innerHTML = randomNick2;
    }
}
p {
    font-size: 20px;
}
<!DOCTYPE  html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" target="_blank" rel="nofollow noreferrer" href="style.css">
    <script src="main.js"></script>
    <title>Nickname Generator</title>
</head>

<body>
    Add your first name: <input type="text" id="name" autocomplete="off">
    <button onclick="generate()">Generate!</button>
    <br>
    <br>
    Your nickname: <p id="demo"></p> 
</body>

</html>

Ad

Answer

The issue was with the initialization of realName variable.

Add .value at the end:

let realName = document.getElementById("name").value;

Also put it inside the generate() function

function generate() {
        let realName = document.getElementById("name").value;
        if (realName === "Alex" || realName === "alex" || realName === "Alexander" || realName === "alexander") {

            let randomNick = randomNicknames[Math.floor(Math.random() * randomNicknames.length)];
            document.getElementById("demo").innerHTML = randomNick;

        } else {

            let randomNick2 = randomNicknames2[Math.floor(Math.random() * randomNicknames2.length)];
            document.getElementById("demo").innerHTML = randomNick2;

        }
        console.log(Math.floor(Math.random() * randomNicknames.length));
    }

You can also use a console.log() to check whether the variable holds the correct value

console.log(realName);

Ad
source: stackoverflow.com
Ad