1. Put these items in an array. var array = ["Horse", "Pig", "Dog", "Cat", "Parrot", "Iguana"];
  2. Generate a random number. var randInt = randomGenerator(0, array.length - 1); ( Generating random whole numbers in JavaScript in a specific range? )
  3. Use the random number to get an item from the array. var item = array[randInt];
  4. Use document.getElementById to get the textbox you want, and use .value = to set the textbox's value. var textbox = document.getElementById("textbox_id").value = randInt;
Answer from Ian on Stack Overflow
Top answer
1 of 3
2

The DOM API you are looking for is: getElementsByClassName

onclick needs to be a function that will be called on click event. What you are doing is calling innerHTML='zufall' immediately, returning the string 'zufall', and assigning onclick='zufall', which is not what you want.

JavaScript array literals are denoted with [] not ().

I'm assuming the string 'zufall' is not what you want, but the variable zufall, which I've adjusted by removing the single quotes.

Math.random() (not random()) returns a random number from 0 to 1. Multiply that by the length and then floor to integer (You could use Math.trunc() also). And then in brackets to access that index in Orte.

Again, variables are set when they are assigned. Which is probably not what you want here. The same thing happens in Python. zufall would be assigned a value that doesn't change unless something is called to update it. This is a common mistake, although as an experienced Python programmer you should not be making this mistake anymore.
I've adjusted it so it updates zufall on every click. As you should be able to see, a global variable is unnecessary. You can just generate the zufall only in the onclick handler.

var Orte = ['a', 'b', 'c']
var zufall = Orte[Math.random()*Orte.length | 0]
button1.onclick = function(){
  zufall = Orte[Math.random()*Orte.length | 0]
  document.getElementsByClassName('text')[0].innerHTML = zufall
}
<div class="text"></div>
<button id="button1">click</button>

2 of 3
1

You can do it with plain JavaScript like this:

var arr1 = ["a", "b", "c"], arr2 = ["d", "e", "f"], arr3 = ["g", "h", "i"];

function showRandomFrom(chosenArray){
  document.getElementsByClassName("text")[0].innerHTML = chosenArray[Math.floor(Math.random() * chosenArray.length)];
}
<div class="text"></div>
<button onclick="showRandomFrom(arr1);">From arr1</button>
<button onclick="showRandomFrom(arr2);">From arr2</button>
<button onclick="showRandomFrom(arr3);">From arr3</button>

Or like this with rando.js if you don't like randomness math:

var arr1 = ["a", "b", "c"], arr2 = ["d", "e", "f"], arr3 = ["g", "h", "i"];
var showRandomFrom = (chosenArray) => document.getElementsByClassName("text")[0].innerHTML = rando(chosenArray).value;
<script src="https://randojs.com/1.0.0.js"></script>
<div class="text"></div>
<button onclick="showRandomFrom(arr1);">From arr1</button>
<button onclick="showRandomFrom(arr2);">From arr2</button>
<button onclick="showRandomFrom(arr3);">From arr3</button>

Also, JavaScript is a different language than Java. The code I've given you is JavaScript.

Discussions

Can JS create truly random words?
I know that JS can select a random value from an array of predefined content. But is it possible for JS to create a truly random word? Without an array that tells it what to choose from? And if so, how can I do that? Iโ€™m using Javascript to code a RNG algorithm for a videogame art project ... More on forum.freecodecamp.org
๐ŸŒ forum.freecodecamp.org
1
0
November 9, 2022
javascript - Generate random list of words with JS - Stack Overflow
I'm trying to build a random JS word list generator but the code I have here just generates a single word. Actually I want it to generate a list of 30 words from a previously given list, it may be ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Generate a random word from an array and then print it to the console log in a function in javascript - Stack Overflow
I am creating hangman in javascript and I have (I think) successfully generated a random word from an array in a function, to check if it works I am trying to print the generated word in to the con... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How can I make a function that chooses a random word everytime I recharge the page?
You could use an external api that returns a different word every time you hit it. You can have a constant of words to map through. This means you'll create a function that returns a random number, between 0 to say length of your words constant array. Then use the random number as index to return the item in the array with that index. Goodluck! More on reddit.com
๐ŸŒ r/learnjavascript
12
1
January 27, 2024
๐ŸŒ
npm
npmjs.com โ€บ package โ€บ random-words
random-words - npm
The underlying implementation of this option utilizes the seedrandom package as a replacement for Math.random(). The count function can be used to calculate the total number of words in the word list that meet the specified minimum and maximum length criteria. ... import { generate, count } from "random-words"; console.log(generate()); //output: 'army' console.log(generate(5)); //output: ['army', 'beautiful', 'became', 'if', 'actually'] console.log(generate({ minLength: 2 })); //output: 'hello' console.log(generate({ maxLength: 6 })); //output: 'blue' console.log(generate({ minLength: 5, maxLe
      ยป npm install random-words
    
Published ย  Jan 25, 2024
Version ย  2.0.1
Author ย  Apostrophe Technologies
๐ŸŒ
freeCodeCamp
forum.freecodecamp.org โ€บ javascript
Can JS create truly random words? - JavaScript - The freeCodeCamp Forum
November 9, 2022 - I know that JS can select a random value from an array of predefined content. But is it possible for JS to create a truly random word? Without an array that tells it what to choose from? And if so, how can I do that? Iโ€™m using Javascript to code a RNG algorithm for a videogame art project ...
Find elsewhere
๐ŸŒ
CodePen
codepen.io โ€บ justpete โ€บ pen โ€บ ogNBPp
Random Word Generator
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
๐ŸŒ
GitHub
github.com โ€บ djbrieck โ€บ get-random-word
GitHub - djbrieck/get-random-word: Given a list of words, a basic javascript function to return a random word each time its called.
Given a list of words, a basic javascript function to return a random word each time its called. - djbrieck/get-random-word
Author ย  djbrieck
๐ŸŒ
GitHub
gist.github.com โ€บ swenzel โ€บ 70beac153cdf23803f89
JavaScript random word generator ยท GitHub
JavaScript random word generator. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
CodePen
codepen.io โ€บ yngve โ€บ pen โ€บ mmWBOv
JavaScript Random Word Generator
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
๐ŸŒ
Articulate
community.articulate.com โ€บ articles โ€บ javascript-random-word-generators-in-elearning
Using JavaScript to Create Random Word Generators in E-Learning #174
July 16, 2017 - It says that I will win the lottery, ... love Javascript. ... I'm a big Game of Thrones fan, it's coming like Winter all the way!! So, in honor of the GoT, I made an example of randomizing a list. This may seem a little different from picking a random number of word but actually, ...
๐ŸŒ
EncodedNA
encodedna.com โ€บ javascript โ€บ random-word-generator.htm
JavaScript Random Word Generator - EncodeDna.com
What's interesting is how it picks up a random word from the list of predefined array. See the below code. let randomIndex = Math.floor(Math.random() * words.length); Array elements in JavaScript are accessed using the index number. The index starts with zero, followed by one and so on.The ...
Top answer
1 of 2
1

I'm going to assume you meant you wanted to generate a random quote and not just one word.

Here's the answer:

const motivation = [{
        quote: "Planting popcorn does not produce more popcorn",
        person: "Farmer Ted"
    }, {
        quote: "White whale, bad whale",
        person: "Confucious (Moby Dick)"
    }, {
        quote: "Use the strobe function to disorientate your attacker",
        person: "Flashlight"
    }, {
        quote: "Apply liberally to your erogenous zones",
        person: "Spice Bomb"
    }, {
        quote: "Help me, I'm bleaching",
        person: "The Great Barrier Reef"
}];

const randomNumber = Math.floor(Math.random() * motivation.length);

console.log(motivation[randomNumber]);

const generate_quote = () => {
  const quote = motivation[randomNumber].quote;
    document.getElementById("random_quote").innerHTML = quote;
}
<p id="random_quote">The random quote will appear here.</p>

<button onclick="generate_quote()">Generate random quote</button>

2 of 2
0

const display = document.getElementById("motivato");

const motivation = [{
  quote: "Planting popcorn does not produce more popcorn",
  person: "Farmer Ted"
}, {
  quote: "White whale, bad whale",
  person: "Confucious (Moby Dick)"
}, {
  quote: "Use the strobe function to disorientate your attacker",
  person: "Flashlight"
}, {
  quote: "Apply liberally to your erogenous zones",
  person: "Spice Bomb"
}, {
  quote: "Help me, I'm bleaching",
  person: "The Great Barrier Reef"
}];

function motivateMe() {
  const listLength = motivation.length;
  const randVal = motivation[Math.floor(Math.random() * listLength)];
  display.innerHTML = `<q>${randVal.quote}</q><br><br><small>${randVal.person}</small>`;
}
<button onclick="motivateMe()">Motivate me!</button>
<h3 id="motivato"></h3>

Now you need to edit the above to make sure that a button press doesn't return the same quote as the previous one, as when it does it seems like the button doesn't work.

Top answer
1 of 2
2

These are a few things you need to follow.

  1. Never use document.write().
  2. Don't self close <div /> tags.
  3. Use event listeners.
  4. Use the scoping correctly. Remove the var here.
  5. Use the parameters wisely. You don't need the parameter here, which makes the global variable, a local one and you aren't passing the value too.

You aren't clear where to show the words. So, I assumed that you wanna show it in the <input />.

words = [
  'Hello',
  'No',
  'Hi',
  'Banana',
  'Apple'
];

function randomWord() {
  document.getElementById("textbox").value = words[Math.floor(Math.random() * words.length)];
}
* {font-family: 'Segoe UI';}
<form name="f1">
  <input type="text" value="" name="textbox" id="textbox" />
  <input type="button" value="show" onclick="randomWord()" />
  <br/>
</form>
<div id="new"></div>

2 of 2
1

You should avoid adding event handlers in view. Instead, use addEventListener.

You should avoid document.write reason

You should also not pass words array as parameter. That can be a part of function that return randomWord

function getRandomWord() {
  var words = [
    'Hello',
    'No',
    'Hi',
    'Banana',
    'Apple'
  ];
  var randomIndex = Math.floor(Math.random() * 10) % words.length;
  return words[randomIndex];
}

function print(str) {
  document.getElementById('new').innerHTML = str;
}

function process(){
  var word = getRandomWord();
  print(word)

}
process()
document.getElementById('btnShow').addEventListener('click', process);
<form name="f1">
  <input type="text" value="" name="textbox" id="textbox" />
  <input type="button" value="show" id="btnShow" />
  <br/>
</form>
<div id="new" />

Top answer
1 of 2
1

It does depend on how the list is "made".

If the list can be made by the programmer (thus static and not be altered by the user), you could do the following (copy and paste this into a .html file):

<html>
  <button onclick="randomizeFunction()">Randomize!!</button>
  
  <p>Random generated word is:</p>
  <p id="randomWord"></p>
</html>

<script>
const myList = ["List item 1", "List item 2", "List item 3", "List item 4", "List item 5"];

randomizeFunction()

function randomizeFunction() {
    document.getElementById("randomWord").innerHTML = myList[Math.floor(Math.random() * myList.length)]
}
</script>

Do note, this uses JavaScript as well! Most responsive websites are driven by it nowadays.

Javascript is the part between the script tags. For you to customize, change the items in const myList, between the [ ... ]. Make sure the [ ... ] stay and seperate items with a comma. Also, if you are to use words, make sure to quote them (making them strings), like I did.

By the way, most people don't mind to get their hands dirty and providing you with an example ('write the whole thing').

Keep going, programming is awesome!

2 of 2
0

You will need javascript for this rather than html. I created a function for you, called Random Word Picker.

if you want to add javascript to a html page put it between these tags

<script> </script>
let theList = ["hello", "there", "john", "how", "are", "you", "doing"]


function randomWordPicker(aList){
    let theListLength = theList.length / 10
    let theAnswer = Math.floor( ( Math.random( ) * 10 ) * theListLength  ) 
    return aList[theAnswer]
}

let result = randomWordPicker(theList)
document.querySelector("h1").innerHTML = result
console.log(result)

this function will pick a random word from the list and then display it to a h1 tag and to the console.