Java Reference
In-Depth Information
All these radio buttons have the same name attribute of " type ". This is used to group
them together―only one radio button can be checked in a group that have the same name.
It also means we can access an HTML collection of all the radio buttons in that group using
this line of code:
Because this is an array-like object, we can use index notation to access each radio button
in the group. For example, the first radio button is:
Each radio button has a value property that is equal its value attribute. We can use this
to set a type property in our hero object to the value of the radio button that is selected.
Add the following code to the makeHero() function in scripts.js:
for (i=0 ; i < form.type.length ; i++) {
if (form.type[i].checked) {
hero.type = form.type[i].value;
This uses a for loop to iterate over the collection of radio buttons to see which one has
been checked. If it is checked, the hero.type property is set to the radio button's value
property. Note the use of the break statement. This is because there is no point continuing
the search for a checked radio button once one has been found since only one of them can
be checked.
Radio buttons also have a checked property that returns the Boolean values true and
false , depending on if it has been selected or not. It's possible to change the checked
property to true , but because only one radio button can be checked at once, all the others
with the same name property will change to false . So the following line of code would
check the " antihero " radio button, but the " hero " and " villain " radio buttons would
then be unchecked:
form.type[2].checked = true;
Search WWH ::

Custom Search