HTML forms--interacting with the user, part two
Notes from May 18, 2005 class
Event watching
The following script demonstrates how the keydown, keypress, keyup, and change events work, and in what order they fire. Visit this working example of the script to see it in action.
<html>
<head><title>Event watching</title><script language="JavaScript" type="text/javascript">
<!--function DisplayEvent(eventName)
/* The name of an event handler gets passed to this script from the textarea1 form field below. This function simply takes that event handler name and adds it to the text that's in the textarea2 form field. */
{
var myMessage = window.document.form1.textarea2.value;
myMessage = myMessage + eventName;
window.document.form1.textarea2.value = myMessage;
}//-->
</script>
</head>
<body><h1>Event watching</h1>
<form name="form1">
<textarea rows="15" cols="40" name="textarea1" onchange="DisplayEvent('onchange\n');" onkeydown="DisplayEvent('onkeydown\n');"
onkeypress="DisplayEvent('onkeypress\n');" onkeyup="DisplayEvent('onkeyup\n');"></textarea>
<!-- note the JavaScript attributes within this textarea HTML tag. This code calls the DisplayEvent() function in the script (above) whenever one of the event handlers (onkeydown, onkeypress, etc.) fires. The value that's passed to the function is just the name of the event that's firing. --><textarea rows="15" cols="40" name="textarea2"></textarea>
<br /><br />
<input type="button" value="Clear Event TextArea" name="button1" onclick="window.document.form1.textarea2.value=''">
<!-- notice this onclick event just executes a line of JavaScript. Normally, we use onclick events to call a function, but since it's just one line of code this time, it's simpler to do it this way.--></form>
</body>
</html>Checkboxes and radio buttons: a computer order form
The following computer order form adds HTML form checkboxes and radio buttons to the mix, and uses all the propreties, methods, and events we've covered in chapter 6 thus far. Visit this working example of the script to see it in action.
<html>
<head><title>Computer order form</title><script language="JavaScript" type="text/javascript">
<!--var radCpuSpeedIndex = 0;
// stores the currently selected index from the radio button groupfunction radCPUSpeed_onclick(radIndex)
/* Triggered when the user selects a radio button for cpu speed. The selected item's index position in the radCPUSPeed[] array gets passed as the parameter (radIndex). -->
{var returnValue = true;
/* the returnValue determines whether the radio button remains checked. If the returnValue is false, it undoes the user's action, thus un-checking the radio button. To allow the user's action to proceed, we return a returnValue of true. */// this if statement happens if the user selects the out-of-stock item
if (radIndex == 1)
{returnValue = false;
alert("Sorry, that processor speed is currently unavailable");
// Next line works around a bug in IE that doesn't cancel the
// Default action properly
document.form1.radCPUSpeed[radCpuSpeedIndex].checked = true;
// resets the checked radio button to the default (3.8 GHz)}
else
{radCpuSpeedIndex = radIndex;
//sets radCpuSpeedIndex to the value the user selected}
return returnValue;
/* returns the value of returnValue to where the function was called, either cancelling the clicking action or allowing it, depending on what CPU speed the user chose */}
function butCheck_onclick()
{var controlIndex;
var element;
var numberOfControls = document.form1.length;
// sets to how many elements are on this form// compSpec builds the string we'll display in the message box
var compSpec = "Your chosen processor speed is ";
compSpec = compSpec + document.form1.radCPUSpeed[radCpuSpeedIndex].value;
compSpec = compSpec + "\nWith the following additional components\n";
// remember, \n just starts a new line/* The following loop looks at every checkbox on the form. If a checkbox is selected, this code adds its value to the compSpec string that's going to tell the user what they selected */
for (controlIndex = 0; controlIndex < numberOfControls; controlIndex++)
{element = document.form1[controlIndex];
if (element.type == "checkbox")
{if (element.checked == true)
{compSpec = compSpec + element.value + "\n";
}
}
}
alert(compSpec);
/* that tiny piece of code pops up the alert box that tells the user what they chose */}
//-->
</script>
</head><body>
<h1>Computer order form</h1>
<form name="form1">
<p>Choose the components you want included on your new computer</p><table>
<tr>
<td>DVD-ROM</td>
<td><input type="checkbox" name="chkDVD" value="DVD-ROM"></td>
</tr>
<tr>
<td>CD-ROM</td>
<td><input type="checkbox" name="chkCD" value="CD-ROM"></td>
</tr>
<tr>
<td>ZIP drive</td>
<td><input type="checkbox" name="chkZip" value="ZIP drive"></td>
</tr>
</table>
<!-- The above is in a table just for formatting purposes. No functions are called, no events are linked.--><p>Select the processor speed you require.</p>
<!-- each radio button below is connected to the same function, radCPUSpeed_onclick().
<table>
<tr>
<td><input type="radio" name="radCPUSpeed" checked onclick="return radCPUSpeed_onclick(0)" value="3.8GHz"></td>
<td>3.8 GHz</td><td><input type="radio" name="radCPUSpeed" onclick="return radCPUSpeed_onclick(1)" value="4.8GHz"></td>
<td>4.8 GHz</td><td><input type="radio" name="radCPUSpeed" onclick="return radCPUSpeed_onclick(2)" value="6GHz"></td>
<td>6 GHz</td>
</tr>
</table>
<input type="button" value="Check Form" name="butCheck" onclick="return butCheck_onclick()">
<!-- This button's onclick value ensures that the butCheck_onclick() function will run when the user clicks the button -->
</form></body>
</html>Adding and subtracting list options from select elements
The HTML <select>... </select> container creates a Select object within JavaScript. That object has an options[] array, made up of an Option object for every <option> element inside the <select> element.
We can use the Select object's selectedIndex property to get an index value, and we can use that information to access the selected option in the options[] array.
To add a new option to a select element, just crete a new Option object using the new operator, and insert it into the options[] array at an empty index position. Two parameters are passed, the text you want to add, and the index value you want to assign it.
var myNewRosterAddition = new Option("Zacharay Zanderbuss", 25)
creates a new Option object for Zachary Zanderbuss, and assigns it a value of 25.
Now that we've created the Option object, we need to add it to an empty array element, like this:
document.myClass.studentRoster.options[25] = myNewRosterAddition
Now Zachary has been added to the roster as 26th on the list. (Remember, arrays start at 0, not 1.) This is fine, as long as there were only 25 people on the roster, otherwise this new code would simply replace whatever was at index item 25. To ensure the addition went into an empty slot at the end, you'd use the .length property to determine how many items are in the array, so you'd know the next available index value.
To remove an element from an array, just reset its value to null.
Here's a kind of silly script that gives you a list of the days of the week, and provides you with two buttons so you can remove or add Wednesday from the list. This is an unlikely example, but it's not a very large leap from this sample to some sort of working roster script that would let you add someone to a list of people, and re-sort the list in the proper order. Visit this working example of the script to see it in action.
<html>
<head><title>Adding and subtracting list options from select elements</title>
<script language="JavaScript" type="text/javascript"><!--
function butRemoveWed_onclick()
{if (document.form1.theDay.options[2].text == "Wednesday")
// make sure "Wednesday" is really there before you try to remove it
{document.form1.theDay.options[2] = null;
// removes this item from the array}
else
{alert("There is no Wednesday here");
}
}
function butAddWed_onclick()
{if (document.form1.theDay.options[2].text != "Wednesday")
// making sure there's not already a "Wednesday" in the array
{// we have to make space in the array to put Wednesday
var indexCounter;
var days= document.form1.theDay;
var lastoption = new Option();
days.options[6] = lastoption;
// creating a new option at the end of the arrayfor (indexCounter = 6;indexCounter > 2; indexCounter--)
{days.options[indexCounter].text = days.options[indexCounter -1].text;
days.options[indexCounter].value = days.options[indexCounter -1].value;
/* this assigns the text and value of all the Option objects from Thursday to Sunday to the Option that is one higher index in the options array, leaving a space at position 2 in the options array into which we can put Wednesday */}
var option = new Option("Wednesday",2);
days.options[2] = option;}
else
{alert("Do you want to have TWO Wednesdays????");
}
}
//-->
</script>
</head>
<body>
<h1>Adding and subtracting list options from select elements</h1>
<form name="form1">
<select name="theDay" size="5">
<option value="0" selected>Monday
<option value="1">Tuesday
<option value="2">Wednesday
<option value="3">Thursday
<option value="4">Friday
<option value="5">Saturday
<option value="6">Sunday
</select>
<br />
<input type="button" value="Remove Wednesday" name="butRemoveWed" onclick="butRemoveWed_onclick()">
<input type="button" value="Add Wednesday" name="butAddWed" onclick="butAddWed_onclick()"></body>
</html>
Homework: using the select element for date difference calculations
Re-read the textbook from the bottom of page 221 to the top of page 228. Create the script on pages 222-223. Can you get it to work? Do you understand how it works? Bring any questions to class on Friday.