Request Dev Services ┬╗

theDevTip.com

Random ‘fill-in-the-blank’ via diff word sets! (JS Demo)

In this exercise; I’ll essentially create a paragraph of text (to demonstrate), with several ‘fill in the blank‘ type boxes within sentences (similar to a mad lib). Each ‘blank space‘ will pool from different allotted set of unique ‘words’ to populate the space when the ‘populate button’ is clicked. There will be a set of words assigned to each different ‘fill in the blank‘. When button is clicked, words will populate and display randomly.


the mark-up: (sample sentence)

<div class="wrap_contain">
  <form NAME="WordForm">  

  <span>Cameron is definitely the <input type=text name="WordBox" id="wordbox" class="fill"></span><span>, when it comes to building those</span> <input type=text name="WordBox2" id="wordbox2" class="fill"></span>,<span> while <input type=text name="WordBox3" id="wordbox3" class="fill"></span><span> out.<BR>

  <input type=button value="Populate" onClick="PickRandomWord(document.WordForm);" id="button">
  </form>
</div>

the JavaScript: (functionality)

var NumberOfWords = 14 // setting word count

// word set 1
var words1 = new BuildArray(NumberOfWords) // build associated array

  words1[1] = "best" // words, values, and placeholders in array
  words1[2] = "most talented"
  words1[3] = "most creative"
  words1[4] = "top notch"
  words1[5] = "coolest"
  words1[6] = "hottest"
  words1[7] = "most amazing"
  words1[8] = "fastest"
  words1[9] = "most rad"
  words1[10] = "funnest"
  words1[11] = "jolliest"
  words1[12] = "Sir Dev Alot"
  words1[13] = "Dr Dev"
  words1[14] = "mejor dise├▒ador"

function BuildArray(size){ // iterate through array
  this.length = size
  for (var i = 1; i <= size; i++){
  this[i] = null}
  return this
}
.......

// call randomly via that click inline click function

function PickRandomWord(frm) {
  // Generate a random number between 1 and NumberOfWords
  var rnd = Math.ceil(Math.random() * NumberOfWords)
  // Display the word inside the text box
  frm.WordBox.value = words1[rnd]
  frm.WordBox2.value = words2[rnd]  
  frm.WordBox3.value = words3[rnd]    
}

Check out the full CodePen demo below! (click populate)

See the Pen Random ‘fill-in-the-blank’ with word sets by Cameron (@camerondevcam) on CodePen.

About the Author
Cameron Cashwell Web Developer
I build websites, web apps, and software. Wanna work together? Let's chat about your project!

Leave a Reply

avatar
  Subscribe  
Notify of