|
To gain more experience working with JavaScript's string and array features, you can create a script that enables the user to enter a list of names, and displays the list in sorted form.
Because this will be a larger script, you will create separate HTML and JavaScript files, as described in Hour 3, "Getting Started with JavaScript Programming." First, the sort.html file will contain the HTML structure and form fields for the script to work with. Listing 5.2 shows the HTML document.
Listing 5.2. The HTML Document for the Sorting Example
<html>
<head>
<title>Array Sorting Example</title>
<script type="text/javascript" language="javascript" src="sort.js">
</script>
</head>
<body>
<h1>Sorting String Arrays</h1>
<p>Enter two or more names in the field below,
and the sorted list of names will appear in the
text area.</p>
<form name="theform">
Name:
<input type="text" name="newname" size="20">
<input type="button" name="addname" value="Add"
onclick="SortNames();">
<br>
<h2>Sorted Names</h2>
<textarea cols="60" rows="10" name="sorted">
The sorted names will appear here.
</textarea>
</form>
</body>
</html>
|
Because the script will be in a separate document, the <script> tag in the header of this document uses the src attribute to include a JavaScript file called sort.js. You will create this file next.
This document defines a form named theform, a text field named newname, an addname button, and a textarea named sorted. Your script will use these form fields as its user interface. Listing 5.3 shows the JavaScript file.
Listing 5.3. The JavaScript File for the Sorting Example
// initialize the counter and the array
var numnames=0;
var names = new Array();
function SortNames() {
// Get the name from the text field
thename=document.theform.newname.value;
// Add the name to the array
names[numnames]=thename;
// Increment the counter
numnames++;
// Sort the array
names.sort();
document.theform.sorted.value=names.join("\n");
}
|
The script begins by defining two variables with the var keyword: numnames will be a counter that increments as each name is added, and the names array will store the names.
When you type a name into the text field and click the button, the onclick event handler calls the SortNames function. This function stores the text field value in a variable, thename, and then adds the name to the names array using numnames as the index. It then increments numnames to prepare for the next name.
The final section of the script sorts the names and displays them. First, the sort() method is used to sort the names array. Next, the join() method is used to combine the names, separating them with line breaks, and display them in the textarea.
To test the script, save it as sort.js, and then load the sort.html file you created previously into a browser. You can then add some names and test the script. Figure 5.2 shows the result after sorting several names.
|