1

So far I get a random word from the list every time I refresh the page, however I want to be able to generate a random word in the textbox with the "show" button. How do I do that? I suppose I should switch out document.write with something else? I've tried onclick instead but it did not work.

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

function randomWord(words) {
  return words[Math.floor(Math.random() * words.length)];
}

for (var x = 0; x < 1; x++)
  document.write(randomWord(words));
<form name="f1">
  <input type="text" value="" name="textbox" id="textbox" />
  <input type="button" value="show" onclick="randomWord()" />
  <br/>
</form>
<div id="new" />
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
Northwood
  • 59
  • 5

2 Answers2

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>
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
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" />
Community
  • 1
  • 1
Rajesh
  • 21,405
  • 5
  • 35
  • 66