Java Reference
In-Depth Information
if (element.type == "checkbox") {
if (element.checked) {
compSpec = compSpec + element.value + "\n";
}
}
}
alert(compSpec);
}
It's here that you loop through each element on the form using
myForm[controlIndex]
, which returns a
reference to the element object stored at the
controlIndex
index position.
You'll see that in this example the
element
variable is set to reference the object stored in the
myForm
collection at the index position stored in variable
controlIndex
. Again, this is for convenient shorthand
purposes; now to use that particular object's properties or methods, you just type
element
, a period,
and then the method or property name, making your code easier to read and debug, which also saves on
typing.
You only want to see which check boxes have been checked, so you use the
type
property, which
every HTML form element object has, to see what element type you are dealing with. If the
type
is
checkbox
, you go ahead and see if it's a checked check box. If so, you append its value to the message
string in
compSpec
. If it is not a check box, it can be safely ignored.
Finally, you use the
alert()
method to display the contents of your message string.
The last function is
getSelectedSpeedValue()
. It doesn't accept any arguments, although you could
generalize this function to accept a collection of
Radio
objects. Doing so would allow you to reuse the
function in multiple projects.
But to get back to the actual code, the first statement of the function creates a
radios
variable that
contains a reference to the
myForm.radCpuSpeed
collection:
function getSelectedSpeedValue() {
var radios = myForm.radCpuSpeed;
Next, you want to find the selected
Radio
object and retrieve its value. You can do this with yet another
for
loop:
for (var index = 0; index < radios.length; index++) {
if (radios[index].checked) {
return radios[index].value;
}
}
return "";
}
The logic is straightforward: Loop through the
radios
collection and check each
Radio
object's
checked
property. If it's
true
, return the value of that
Radio
object, but if the loop exits without
finding a
checked Radio
object, you return an empty string.