Using form controls to set function pointers.

The examples below show radio buttons and a <select> (list box) control being used to choose targets for function pointers. In both cases, the controls generate an integer value, which is used as a subscript for an array of pointers. A pointer variable is then set equal to the subscripted element's value, and becomes a pointer to the appropriate function.

This page works in version 4.0 and later of Netscape and Microsoft browsers.

Using radio buttons to select a difficulty level for a quiz.

Choose a difficulty level:
Easy    Medium    Hard

This page contains three 'question-asking' functions, called easy(), medium() and hard(). An array of pointers to these functions is created by this statement:

diffOptions = new Array(easy, medium, hard)

Changes in the radio group's selection are trapped by adding an onclick= event handler to each <input type="radio"> tag.  Here's the onclick event handler for the first button:

onClick="setDifficulty(0)"

the function setDifficulty() does this:

function setDifficulty(diffLevel) {
  askQuestion = diffOptions[diffLevel]
  askQuestion("init")
}

Using a drop-down list to select a language

 

Using a drop-down list is very similar. Here's the statement which builds an array of pointers to the language functions:

langOptions = new Array(english, french, spanish, american)

List boxes (<select> tags) expose a .selectedIndex property, which indicate the current-selected option (starting from zero). Here's the the <select> tag:

<select size="1" name="language" onchange="changeLanguage(this.selectedIndex)">

And here's the function changeLanguage():

function changeLanguage(langNo) {
  doMessage = langOptions[langNo]
  doMessage("init") }

In Internet Explorer 4.0 or later, you could respond to a change of language by replacing all the on-screen text (for example "Div1.innerHTML = Div1Spanish.innerHTML"). If you want to do that in Netscape though, you'll have to wait for Mozilla!