Web Development Tutorials




  
  

Composing Script References

As an introduction to this topic, take a look at the following script which sums the five values shown in the five textboxes.

+ + + + =

Figure 5-9. Summing the values of five textboxes.

function doSum() {
  document.getElementById("sumOutput").value = 
    parseInt(document.getElementById("no1").value) + 
    parseInt(document.getElementById("no2").value) + 
    parseInt(document.getElementById("no3").value) + 
    parseInt(document.getElementById("no4").value) + 
    parseInt(document.getElementById("no5").value)
}

function init() {
  var doSumBtn = document.getElementById("doSumBtn");
  doSumBtn.onclick=doSum;
}

window.onload=init;

<input type="text" id="no1" style="width:20px" value="10"/> +
<input type="text" id="no2" style="width:20px" value="20"/> +
<input type="text" id="no3" style="width:20px" value="30"/> +
<input type="text" id="no4" style="width:20px" value="40"/> +
<input type="text" id="no5" style="width:20px" value="50"/> =
<input type="text" id="sumOutput" style="width:30px"/> 
<input type="button" value="Sum" id="doSumBtn" />

Listing 5-12. Code to sum the values of five textboxes.

You should recogize the script as adding together the numeric values in the five boxes and assigning the result to the Sum box. There is nothing problematic about the script...except when there are dozens of such page elements to reference. That would make for a lot of typing and a very long script to reference each textbox or other page element individually.

Also consider the reverse situation. Click the following button to programmatically create a set of textboxes.



Figure 5-10. Creating a set of textboxes.

function makeBoxes() {
  document.getElementById("boxArea").innerHTML = ""
  document.getElementById("boxArea").innerHTML += 
	"<input type='text' id='box1' style='width:20px'/> + "
  document.getElementById("boxArea").innerHTML += 
	"<input type='text' id='box2' style='width:20px'/> + "
  document.getElementById("boxArea").innerHTML += 
	"<input type='text' id='box3' style='width:20px'/> + "
  document.getElementById("boxArea").innerHTML += 
	"<input type='text' id='box4' style='width:20px'/> + "
  document.getElementById("boxArea").innerHTML += 
	"<input type='text' id='box5' style='width:20px'/> "
}

function init() {
  var makeBoxesBtn = document.getElementById("makeBoxesBtn");
  makeBoxesBtn.onclick=makeBoxes;
}

window.onload=init;


<input type="button" value="Make Boxes" id="makeBoxesBtn" />
<div id="boxArea"></div>

Listing 5-13. Code to create a set of textboxes.

Again, no problem if you are creating a half-dozen or so page elements. But consider the scripting chore if you needed to create a page full of similar elements - a lot of typing and a lot of script.

You might be thinking, then, why not do these kinds of things in a loop? Code one addition operation and repeat it for as many textboxes as required; or code one textbox HTML tag and repeat it for as many texboxes as needed. If that's what you're thinking, then you're on the right track!

Scripted Element References

Notice that the id values of the summed textboxes above are no1, no2, no3, no4, and no5. Thus, it is quite easy to construct these ids in a loop as a way to reference their values.

function doSum() {
  var theSum = 0;
  for (i=1; i<=5; i++) {
    theSum += parseInt(document.getElementById("no" + i).value);
  }
  document.getElementById("sumOutput").value = theSum;
}

Listing 5-14. Alternate code to sum the values of textboxes.

Index i is concatenated with the string "no" to compose the id of a textbox whose value is then added to variable theSum. That is, iterate the loop five times to compose the five references,

document.getElementById("no1").value
document.getElementById("no2").value
document.getElementById("no3").value
document.getElementById("no4").value
document.getElementById("no5").value

Each of whose value is added to theSum. In this fashion, any number of values can be added with a single addition operation.

As long as id values have a common component string along with an iterate-able value appended to it, a loop can be used to iterate through any number of like-named elements, saving from having to refer to them individually. The script itself can write the code to refer to page elements.

Scripted HTML Tags

When creating a series of textboxes (or any other page elements) programmatically, you do not have to worry about converting strings to references. You can simply concatenate HTML, text, and variables and assign them to the innerHTML property of the display area. The HTML portion is automatically rendered as HTML code and associated id values. For example, the following code creates a series of textboxes with unique id values by concatenation the loop index i within the HTML strings.

for (i=1; i<=5; i++) {
  document.getElementById("boxArea").innerHTML +=
    "<input type='text' id='box" + i + "' style='width:20px'/><br/>";
}

Listing 5-15. Code to create a series of textboxes.

In the above script, when i = 1, the following string is written to the innerHTML property of the output area.

"<input type='text' id='box1' style='width:20px'/><br/>"

The string is interpreted as HTML code and a textbox control with id='box1' is displayed on the page.

An Example

The loop-controlled tag creation and reference techniques are brought together below to create a series of textboxes and to sum their values. You can enter a number between 1 and 10 to choose the number of textboxes to create. Example values are created for the textboxes. You can enter your own values to sum.

No. of Boxes:

Figure 5-11. Creating and summing a set of textboxes with script.


function createBoxes() {
  //-- Check for a number between 1 and 10
  if (parseInt(document.getElementById("noBoxes").value) >= 1 && 
      parseInt(document.getElementById("noBoxes").value) <= 10) 
  {
    //-- Clear the output area
    document.getElementById("displayArea").innerHTML = "";

    //-- Create labels and textbox tags and append to output area
    for (i=1; i<=document.getElementById("noBoxes").value; i++) {
      document.getElementById("displayArea").innerHTML += 
        "<span style='width:60px'>Value " + i + ": </span>" +
        "<input id='myBox" + i + "' type='text' value='" + (i*10) + "' " +
        "style='width:40px;text-align:right'/><br/>";
    }
		
    //-- Create a button and output area
    document.getElementById("displayArea").innerHTML +=
      "<input type='button' value='Total ' onclick='getTotal()' " +
      "style='width:57px; font-size:8pt'/> ";
    document.getElementById("displayArea").innerHTML +=
      "<input id='total' type='text' style='width:40px;text-align:right'/>";
  }
}

function getTotal() {
  //-- Iterate the textboxes and sum their values; display the total
  var total = 0;
  for (i=1; i<=document.getElementById("noBoxes").value; i++) {
    total += parseInt(document.getElementById("myBox" + i).value);
  }
  document.getElementById("total").value = total;
}

function init() {
  var createBoxesBtn = document.getElementById("createBoxesBtn");
  createBoxesBtn.onclick=createBoxes;
}

window.onload=init;

No. of Boxes: 
<input type="text" id="noBoxes" value="7"
  style="width:30px; text-align:right"/>
<input type="button" value="Create Boxes" id="createBoxesBtn" />
<div id="displayArea"></div>

Listing 5-16. Code to create and sum a series of textboxes with script.

The interesting thing about this application is that all HTML codes are created by the script. In the createBoxes() function, all of the textboxes are created along with their text labels, along with the button that calls the getTotal() function. As you view the script pay attention to how the loop index i is integrated with the HTML code. It is used as part of the "Value" label, as part of the id value for the textbox, and to generate a value (i * 10) to appear in the textbox. Also notice how the number entered in the above box is used as the ending loop value of i. The first part of the script makes sure that the entered value is between 1 and 10.

The getTotal() function iterates through the same number of textboxes, adding their values to variable total. Index i is used to compose an id value for referencing the textboxes.

Although it can be a bit tricky putting together strings and variables to create HTML code with script, it does save time and effort in the long run; plus, there are certain situations, particularly involving an unknown or variable number of page elements, where it must be done. Once you have mastered the techniques, though, you can't do without them.


TOP | NEXT: Chapter 6 - Arrays