jeudi 21 septembre 2017

Use Dropdown List Value to Modify Array Used in Random Word Generator

Using Javascript on a blogger blog to create a random word generator for kids in my classes to practice reading their words at home.

What I Want to Do

Generate a random word from a list of 5 words that starts from the first word selected. If there are less than 5 words left then it just picks from the remaining words.

So if the kid selects the 3rd word from the dropdown list, I want the generator to pick a random word from #3-7 (total of 5 words). If the kid selects the 8th word then the generator would only pick from words #8-10 (total of three words) since those are the only ones left.

What I Figured Out How To Do

Created a dropdown list of all the words (there are actually 100+ words)

<select id="words" name="wordlist">
<option selected="" value="0">1. sat</option>
<option value="1">2. rat</option>
<option value="2">3. set</option>
<option value="3">4. ret</option>
<option value="4">5. sit</option>
<option value="5">6. rit</option>
<option value="6">7. sot</option>
<option value="7">8. rot</option>
<option value="8">9. sut</option>
<option value="9">10. rut</option>
</select>

A word box with a button that fills the box with a random word from the array in the javascript.

<form 100="" name="WordForm" width:="">

<input id="wordbox" name="WordBox" readonly="" style="box-sizing: border-box; font-size: 60pt; height: auto; text-align: center; width: 100%;" type="TEXT" />

<input id="button" onclick="PickRandomWord(document.WordForm);" style="background-color: mintcream; display: block; font-size: 30px; height: 50px; margin: auto; width: 200px;" type="BUTTON" value="Click Me!" />
</form>

Javascript that randomly picks a word from the array given.

<script>
var words = new Array("sat","rat","set","ret","sit","rit","sot","rot","sut","rut")
function PickRandomWord(frm) {
var rnd = words[Math.floor(Math.random() * words.length)];
frm.WordBox.value = rnd
}
 </script>

Possible Solutions:

With my limited knowledge I came up with the following solutions, but couldn't make them work:

  • Given an array with all possible words, create a spliced array that changes depending on what the first word is. The generator will always pick from that spliced array.
  • A whole bunch of switch case statements with a new array for each possible option in the dropdown list. The generator picks from a different array depending on what option is selected.



Aucun commentaire:

Enregistrer un commentaire