Pages

Thursday, November 3, 2011

Process forms more easily by synchronizing numeric field values with JavaScript arrays

You may want to display information based on a visitor's form field selection. For instance, a dropdown list or radio button group may trigger specific text to appear in a designated element on the page. Naturally, you could force the page to reload with the new information each time the user selects an option, but JavaScript offers a better, client-side solution:



  1. Fill a JavaScript array with all the information associated with the various form fields.
  2. When the visitor makes a selection, use client-side script to pull the appropriate information and display it.
With this kind of system, it's best to synchronize the array indexes with the form field values. That way, you can simply plug in the value as the array index, and--voila!--you've retrieved the appropriate information. Here's a page demonstrating how this works:

<html><head><script type="text/javascript">
    var barks = new Array()
    barks[1] = "wwwWoof! wwwWoof-woof? "
    barks[2] = "Arf! Arf! Rf!"
    barks[3] = "ruff-Ruff! ruff-Ruff!"

    function showBark(val) {
      alert(barks[val])
    }
</script>
<body>

<input type="radio" name="barks"
    onclick="showBark(this.value)"
    value="1">Spot</input>
<input type="radio" name="barks"
    onclick="showBark(this.value)"
    value="2">Spottie</input>
<input type="radio" name="barks"
    onclick="showBark(this.value)"
    value="3">Caesar</input>
</body></html>


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.