-1

I'm trying to create a random username generator, when the users click on ''gen-button'' it should give them a random username. im new to javascript so help would be appreciated :)

var nameList = [
  'Time', 'Past', 'Future', 'Dev',
  'Fly', 'Flying', 'Soar', 'Soaring', 'Power', 'Falling',
  'Fall', 'Jump', 'Cliff', 'Mountain', 'Rend', 'Red', 'Blue',
  'Green', 'Yellow', 'Gold', 'Demon', 'Demonic', 'Panda', 'Cat',
  'Kitty', 'Kitten', 'Zero', 'Memory', 'Trooper', 'XX', 'Bandit',
  'Fear', 'Light', 'Glow', 'Tread', 'Deep', 'Deeper', 'Deepest',
  'Mine', 'Your', 'Worst', 'Enemy', 'Hostile', 'Force', 'Video',
  'Game', 'Donkey', 'Mule', 'Colt', 'Cult', 'Cultist', 'Magnum',
  'Gun', 'Assault', 'Recon', 'Trap', 'Trapper', 'Redeem', 'Code',
  'Script', 'Writer', 'Near', 'Close', 'Open', 'Cube', 'Circle',
  'Geo', 'Genome', 'Germ', 'Spaz', 'Shot', 'Echo', 'Beta', 'Alpha',
  'Gamma', 'Omega', 'Seal', 'Squid', 'Money', 'Cash', 'Lord', 'King',
  'Duke', 'Rest', 'Fire', 'Flame', 'Morrow', 'Break', 'Breaker', 'Numb',
  'Ice', 'Cold', 'Rotten', 'Sick', 'Sickly', 'Janitor', 'Camel', 'Rooster',
  'Sand', 'Desert', 'Dessert', 'Hurdle', 'Racer', 'Eraser', 'Erase', 'Big',
  'Small', 'Short', 'Tall', 'Sith', 'Bounty', 'Hunter', 'Cracked', 'Broken',
  'Sad', 'Happy', 'Joy', 'Joyful', 'Crimson', 'Destiny', 'Deceit', 'Lies',
  'Lie', 'Honest', 'Destined', 'Bloxxer', 'Hawk', 'Eagle', 'Hawker', 'Walker',
  'Zombie', 'Sarge', 'Capt', 'Captain', 'Punch', 'One', 'Two', 'Uno', 'Slice',
  'Slash', 'Melt', 'Melted', 'Melting', 'Fell', 'Wolf', 'Hound',
  'Legacy', 'Sharp', 'Dead', 'Mew', 'Chuckle', 'Bubba', 'Bubble', 'Sandwich', 'Smasher', 'Extreme', 'Multi', 'Universe', 'Ultimate', 'Death', 'Ready', 'Monkey', 'Elevator', 'Wrench', 'Grease', 'Head', 'Theme', 'Grand', 'Cool', 'Kid', 'Boy', 'Girl', 'Vortex', 'Paradox'
];
function generate() {
var finalName = nameList[Math.floor(Math.random() * nameList.length)];
      document.getElementById('uNameInput').value = finalName;
    };
<input id="uNameInput" class="choosename" type="text" maxlength="12" minlength="4" placeholder="username" required>

<input onclick="generate()" id="gen-button" class="modern" type="button" value="Generate usename" </input>
EMILO
  • 271
  • 4
  • 12
  • `TypeError: finalName is not a function` You cannot reference a variable as `finalName()`. Those parentheses are for functions. – vahdet Feb 15 '19 at 11:47

3 Answers3

4

As reported in the console finalName is not a function. the variable finalName only contains a string with the random name.

then you need to change the value property of the input uNameInput.

    
        var nameList = [
                'Time','Past','Future','Dev',
                'Fly','Flying','Soar','Soaring','Power','Falling',
                'Fall','Jump','Cliff','Mountain','Rend','Red','Blue',
                'Green','Yellow','Gold','Demon','Demonic','Panda','Cat',
                'Kitty','Kitten','Zero','Memory','Trooper','XX','Bandit',
                'Fear','Light','Glow','Tread','Deep','Deeper','Deepest',
                'Mine','Your','Worst','Enemy','Hostile','Force','Video',
                'Game','Donkey','Mule','Colt','Cult','Cultist','Magnum',
                'Gun','Assault','Recon','Trap','Trapper','Redeem','Code',
                'Script','Writer','Near','Close','Open','Cube','Circle',
                'Geo','Genome','Germ','Spaz','Shot','Echo','Beta','Alpha',
                'Gamma','Omega','Seal','Squid','Money','Cash','Lord','King',
                'Duke','Rest','Fire','Flame','Morrow','Break','Breaker','Numb',
                'Ice','Cold','Rotten','Sick','Sickly','Janitor','Camel','Rooster',
                'Sand','Desert','Dessert','Hurdle','Racer','Eraser','Erase','Big',
                'Small','Short','Tall','Sith','Bounty','Hunter','Cracked','Broken',
                'Sad','Happy','Joy','Joyful','Crimson','Destiny','Deceit','Lies',
                'Lie','Honest','Destined','Bloxxer','Hawk','Eagle','Hawker','Walker',
                'Zombie','Sarge','Capt','Captain','Punch','One','Two','Uno','Slice',
                'Slash','Melt','Melted','Melting','Fell','Wolf','Hound',
                'Legacy','Sharp','Dead','Mew','Chuckle','Bubba','Bubble','Sandwich','Smasher','Extreme','Multi','Universe','Ultimate','Death','Ready','Monkey','Elevator','Wrench','Grease','Head','Theme','Grand','Cool','Kid','Boy','Girl','Vortex','Paradox'
            ];
        
            var finalName = ""
        
            function generate() {
               var finalName = nameList[Math.floor( Math.random() * nameList.length )];
               document.getElementById("uNameInput").value = finalName;
            };
    <input id="uNameInput" class="choosename" type="text" maxlength="12" minlength="4" placeholder="username" required>
            
    <input onclick="generate()" id="gen-button" class="modern" type="button" value="Generate usename"</input>
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
1

First, input elements don't have a closing tag.

Next, you are trying to assign the .innerHTML to the return value of finalName, which at that point in your code is an empty string, thus causing the finalName is not a function error. Event still, input elements don't have any .innerHTML, they have a value property so, all you need to do is assign the value of the input to the result of the random operation.

Also, you should not use inline HTML event attributes, such as onclick. There are a bunch of reasons not to use this 20+ year old technique that just will not die the death it deserves. Instead, follow modern standards and separate your HTML from your JavaScript and use .addEventListener() to register DOM events.

One last item (and it's more of a UI design suggestion than anything else), since you are going to be populating the field, it seems unlikely that you'd want the user to be able to change the randomly assigned value. If that is the case, don't use a form field of any kind in the first place. You can use a regular DOM element, such as a <span> and in that scenario, you would simply set the .textContent of the span to the random name instead of the value of the input. I've added that example to the answer.

var nameList = [
  'Time','Past','Future','Dev',
  'Fly','Flying','Soar','Soaring','Power','Falling',
  'Fall','Jump','Cliff','Mountain','Rend','Red','Blue',
  'Green','Yellow','Gold','Demon','Demonic','Panda','Cat',
  'Kitty','Kitten','Zero','Memory','Trooper','XX','Bandit',
  'Fear','Light','Glow','Tread','Deep','Deeper','Deepest',
  'Mine','Your','Worst','Enemy','Hostile','Force','Video',
  'Game','Donkey','Mule','Colt','Cult','Cultist','Magnum',
  'Gun','Assault','Recon','Trap','Trapper','Redeem','Code',
  'Script','Writer','Near','Close','Open','Cube','Circle',
  'Geo','Genome','Germ','Spaz','Shot','Echo','Beta','Alpha',
  'Gamma','Omega','Seal','Squid','Money','Cash','Lord','King',
  'Duke','Rest','Fire','Flame','Morrow','Break','Breaker','Numb',
  'Ice','Cold','Rotten','Sick','Sickly','Janitor','Camel','Rooster',
  'Sand','Desert','Dessert','Hurdle','Racer','Eraser','Erase','Big',
  'Small','Short','Tall','Sith','Bounty','Hunter','Cracked','Broken',
  'Sad','Happy','Joy','Joyful','Crimson','Destiny','Deceit','Lies',
  'Lie','Honest','Destined','Bloxxer','Hawk','Eagle','Hawker','Walker',
  'Zombie','Sarge','Capt','Captain','Punch','One','Two','Uno','Slice',
  'Slash','Melt','Melted','Melting','Fell','Wolf','Hound',
  'Legacy','Sharp','Dead','Mew','Chuckle','Bubba','Bubble','Sandwich',
  'Smasher','Extreme','Multi','Universe','Ultimate','Death','Ready','Monkey',   'Elevator','Wrench','Grease','Head','Theme','Grand','Cool','Kid','Boy',
   'Girl','Vortex','Paradox'
];

// Get a reference to the element that needs an event handler
// and the element(s) that needs the output
let btn = document.getElementById("gen-button");
let output = document.getElementById("uNameInput");  
let output2 = document.querySelector(".randomName");

// Set up the event handler
btn.addEventListener("click", generate);

function generate() {
  // The function doesn't need to "return" anything. It just needs
  // to set the value of the text field to the random name.
  let result = nameList[Math.floor( Math.random() * nameList.length )];
  output.value = result;   // <-- form fields have a value
  output2.textContent = result; // non-form elements have textContent
};
.randomName { background-color:#ff0; font-weight:bold; }
<input id="uNameInput" class="choosename" type="text" maxlength="12" minlength="4" placeholder="username" required>
<input id="gen-button" class="modern" type="button" value="Generate usename">
<br>
<!-- Just for demonstration -->
Your randomly assigned name is: <span class="randomName"></span>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

Here is a list of all the mistakes you did:

  • Inputs don't have innerHTML, you should change the value property instead
  • You are assigning the name using finalName() instead of finalName (fieldName is a string, not a function)
  • You assign the value before setting finalName so you were setting the value to be an empty string (or the previously selected name) instead of the new name
  • The correct format for input is: <input> or <input /> rather than the usual <div></div>
  • You are trying to update the value of the button rather than the value of the text input
  • I also removed the global variable finalName since it wasn't useful (even if you want to store the name, you can just get it from the value of the input)
  • A small syntax error (which will not throw an error) is that you added a semicolon you didn't need to add after the generate function declaration. You only need to add semicolons to function declarations when you are "declaring" them using a function expression (var generate = function(){};)

Here is a working version of your code:

var nameList = [
  'Time', 'Past', 'Future', 'Dev',
  'Fly', 'Flying', 'Soar', 'Soaring', 'Power', 'Falling',
  'Fall', 'Jump', 'Cliff', 'Mountain', 'Rend', 'Red', 'Blue',
  'Green', 'Yellow', 'Gold', 'Demon', 'Demonic', 'Panda', 'Cat',
  'Kitty', 'Kitten', 'Zero', 'Memory', 'Trooper', 'XX', 'Bandit',
  'Fear', 'Light', 'Glow', 'Tread', 'Deep', 'Deeper', 'Deepest',
  'Mine', 'Your', 'Worst', 'Enemy', 'Hostile', 'Force', 'Video',
  'Game', 'Donkey', 'Mule', 'Colt', 'Cult', 'Cultist', 'Magnum',
  'Gun', 'Assault', 'Recon', 'Trap', 'Trapper', 'Redeem', 'Code',
  'Script', 'Writer', 'Near', 'Close', 'Open', 'Cube', 'Circle',
  'Geo', 'Genome', 'Germ', 'Spaz', 'Shot', 'Echo', 'Beta', 'Alpha',
  'Gamma', 'Omega', 'Seal', 'Squid', 'Money', 'Cash', 'Lord', 'King',
  'Duke', 'Rest', 'Fire', 'Flame', 'Morrow', 'Break', 'Breaker', 'Numb',
  'Ice', 'Cold', 'Rotten', 'Sick', 'Sickly', 'Janitor', 'Camel', 'Rooster',
  'Sand', 'Desert', 'Dessert', 'Hurdle', 'Racer', 'Eraser', 'Erase', 'Big',
  'Small', 'Short', 'Tall', 'Sith', 'Bounty', 'Hunter', 'Cracked', 'Broken',
  'Sad', 'Happy', 'Joy', 'Joyful', 'Crimson', 'Destiny', 'Deceit', 'Lies',
  'Lie', 'Honest', 'Destined', 'Bloxxer', 'Hawk', 'Eagle', 'Hawker', 'Walker',
  'Zombie', 'Sarge', 'Capt', 'Captain', 'Punch', 'One', 'Two', 'Uno', 'Slice',
  'Slash', 'Melt', 'Melted', 'Melting', 'Fell', 'Wolf', 'Hound',
  'Legacy', 'Sharp', 'Dead', 'Mew', 'Chuckle', 'Bubba', 'Bubble', 'Sandwich', 'Smasher', 'Extreme', 'Multi', 'Universe', 'Ultimate', 'Death', 'Ready', 'Monkey', 'Elevator', 'Wrench', 'Grease', 'Head', 'Theme', 'Grand', 'Cool', 'Kid', 'Boy', 'Girl', 'Vortex', 'Paradox'
];

document.querySelector("#gen-button").addEventListener("click", generate);

function generate() {
  return document.querySelector("#uNameInput").value = nameList[Math.floor(Math.random() * nameList.length)];
}
<input id="uNameInput" class="choosename" type="text" maxlength="12" minlength="4" placeholder="username" required>

<input id="gen-button" class="modern" type="button" value="Generate usename" />
nick zoum
  • 7,216
  • 7
  • 36
  • 80
  • *The correct format for input is: * Actually, the correct format is: ``. XHTML is rarely used these days and technically, the slash at the end of an opening tag is not recognized by the HTML parser anyway. That syntax is really only beneficial when the code is parsed by an XML parser. – Scott Marcus Feb 15 '19 at 12:01
  • Also (FYI) *You only need to add semicolons to function declarations when you are declaring them like this: var generate = function(){};* <-- That's not a function ***declaration*** that's a function ***expression***. – Scott Marcus Feb 15 '19 at 12:12
  • @ScottMarcus It's a function declaration that is being assigned to a variable. The semicolon is needed for the assignment. Also I edited the answer regarding `` – nick zoum Feb 15 '19 at 12:24
  • A function that is assigned to a variable is called a `function expression`. A function declaration is something different. There are important [differences between the two](https://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/) regarding hoisting and depending on the declaration variable used, temporal dead zones. Also, the semicolon has nothing to do with the assignment. Semicolons are statement terminators. It doesn't matter what the statement is doing. – Scott Marcus Feb 15 '19 at 12:27
  • @ScottMarcus I never denied that it's not a function expression, but you said that it's also not a declaration. That's not true since you are still declaring a function (anonymous or not). – nick zoum Feb 15 '19 at 12:29
  • It's *not* a function declaration. It's a variable assignment that is *assigning* a function. It's very important to understand the difference. – Scott Marcus Feb 15 '19 at 12:30
  • You are still declaring a function with the `function (){}` part. Which you can access from inside the function (assuming it's not anonymous) – nick zoum Feb 15 '19 at 12:31
  • That may be what you are *doing*, but that's not what you call the syntax. Calling a function expression a function declaration is not accurate and can lead to confusion. – Scott Marcus Feb 15 '19 at 12:32
  • I'm just saying that a function expression is composed from an assignment and a function declaration. Thus saying `assignment and a function declaration` instead of `function expression` is not wrong, since they are the same thing. – nick zoum Feb 15 '19 at 12:33
  • Understood. And I'm just saying (especially since this is a platform that many use as a learning tool) that it's important that we use the right terminology because, in this case, it's incorrect to call the code you've shown a *function declaration* when that term has a specific meaning in JavaScript. – Scott Marcus Feb 15 '19 at 12:36
  • @ScottMarcus Fair enough, I changed my answer – nick zoum Feb 15 '19 at 12:37