- Put these items in an array.
var array = ["Horse", "Pig", "Dog", "Cat", "Parrot", "Iguana"]; - Generate a random number.
var randInt = randomGenerator(0, array.length - 1);( Generating random whole numbers in JavaScript in a specific range? ) - Use the random number to get an item from the array.
var item = array[randInt]; - Use
document.getElementByIdto get the textbox you want, and use.value =to set the textbox's value.var textbox = document.getElementById("textbox_id").value = randInt;
- Put these items in an array.
var array = ["Horse", "Pig", "Dog", "Cat", "Parrot", "Iguana"]; - Generate a random number.
var randInt = randomGenerator(0, array.length - 1);( Generating random whole numbers in JavaScript in a specific range? ) - Use the random number to get an item from the array.
var item = array[randInt]; - Use
document.getElementByIdto get the textbox you want, and use.value =to set the textbox's value.var textbox = document.getElementById("textbox_id").value = randInt;
You just use Math.random() and index into the array of words.
var words = ['Horse',
'Pig',
'Dog',
'Cat',
'Parrot',
'Iguana'
];
function randomWord(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
for(var x=0; x<20; x++)
console.log(randomWord(words));
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>
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.
Can JS create truly random words?
javascript - Generate random list of words with JS - Stack Overflow
Generate a random word from an array and then print it to the console log in a function in javascript - Stack Overflow
How can I make a function that chooses a random word everytime I recharge the page?
Videos
Use:
var things = ['Rock', 'Paper', 'Scissor'];
var thing = things[Math.floor(Math.random()*things.length)];
alert('The computer chose:' + thing);
Demonstration
Just to precisely answer your question, supposing you really want to keep your three global variables, you could do this:
var c = "Rock";
var d = "Paper";
var e = "Scissors";
var thing = window['cde'.charAt(Math.floor(Math.random()*3))];
document.write('The computer chose: ' + thing);
Demonstration
(But don't.)
You can use Math.random() to get a random number beteween 0 and 1.
If you want a whole random number between 0 and 2. (so: 0, 1 or 2). You can use:
Math.floor(Math.random()*3);
Note that Math.round (instead of floor) would be wrong here since the edge values will have a lower chance, and you might actually get 3 as well.
ยป npm install random-words
Here is an example on jsfiddle
var words = ["monitor", "program", "application", "keyboard", "javascript", "gaming", "network"];
var word = words[Math.floor(Math.random() * words.length)];
console.log(word);
document.getElementById("word").textContent = word;
And to have it fit in directly with you present code:
var getRandomWord = function () {
return words[Math.floor(Math.random() * words.length)];
};
Try using it this way:
var getRandomWord = (function () {
var gameWordArray = [];
gameWordArray.push("monitor");
gameWordArray.push("program");
gameWordArray.push("application");
gameWordArray.push("keyboard");
gameWordArray.push("javascript");
gameWordArray.push("gaming");
gameWordArray.push("network");
return function () {
var randNum, finalWord;
randNum = Math.floor(Math.random() * gameWordArray.length);
finalWord = gameWordArray[randNum];
return finalWord;
};
})();
DEMO: http://jsfiddle.net/bCEFA/1/
Instead of declaring an array with a predefined length, you might as well declare an empty one and add values to the end of it (with .push()). You could've also declared the array like:
var gameWordArray = ["monitor", "program", ...];
You were trying to print word (which I renamed to getRandomWord), which was/is a function. You probably meant to use console.log(gameWordArray[randno]), which should work.
It's basically a wordle. I want it to choose a random word, how can I do that?
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>
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.
These are a few things you need to follow.
- Never use
document.write(). - Don't self close
<div />tags. - Use event listeners.
- Use the scoping correctly. Remove the
varhere. - 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>
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" />
As mentioned in my comment, store the quotes in an array, then add a click handler that selects at random from that array.
Give your button an id, so it can easily be selected from JS:
<button id="changeQuote">Change Quote</button>
Then something like this, using the Math.random() method:
var quotes = [
"The quick brown fox jumps over the lazy dog.",
"Look out! There are llamas!",
"No, really, don't get up.",
"Whatever",
"Etc."
];
document.getElementById("changeQuote").addEventListener("click", function() {
var q = quotes[ Math.floor( Math.random() * quotes.length ) ];
document.getElementById("test").innerHTML = q;
});
Demo: http://jsfiddle.net/9pqqmnrs/
Further reading:
Math.random()Math.floor().addEventListener()
Easy way:
<p id="test"></p>
<script>
var quotes = ["quote 1", "quote 2", "quote 3", "quote 4", "quote 5"];
var index = Math.floor((Math.random() * quotes.length));
document.getElementById('test').innerHTML = quotes[index];
</script>
Explanation: Quotes are stored as array. Math functions used to determine which random number will be generated based on the quotes array length. See also: http://www.w3schools.com/jsref/jsref_random.asp
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!
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.