Inserting Text into a Document, using
This text changes
When I click on a radio button the text changes. That is, the words change, and so does
the colour and the size of the text.
To make the code work, you must first give each of the three radio buttons the same
name, and different IDs. And the paragraph you wish to change should be given a unique ID:
< input type="radio" id="myRadio1" name="C1" value="jav" onclick="modifyText('myRadio1')" />
< br />
Ice cream
< input type="radio" id="myRadio2" name="C1" value="ice" onclick="modifyText('myRadio2')" />
< br />
Swimming
< input type="radio" id="myRadio3" name="C1" value="swim" onclick="modifyText('myRadio3')" />
Each of the radio buttons above has a distinct ID. This ID is used to call the function
"modifyText" to make the changes.
The HTML code for the paragraph is:
<p id="myPara1"
class="vanilla">This
text changes</p>
So far we have completed the code in the BODY section of the page. All that remains is
the function and STYLE in the HEAD section. The style is:
<style type= "text/css">
<!--
.vanilla {color: #8000FF; font-weight: bold;};
.bluey {color:blue; font-size:30; font-family:monospace };
.reddy {color:red; font-size:24; font-family:fantasy};
.greeny {color:green; font-size:40;font-family:cursive};
-->
</style>
We have defined four classes for the style (one class is the original one for the
paragraph, and could be omitted).
Finally, here is the function:
<script type= "text/javascript">
<!--
//the code detects which radio button has been checked
//when the user clicks and changes the style and content
//of a paragraph
function modifyText(myRadio)
{
var para =
document.getElementById('myPara1');
var
theRadioValue=document.getElementById(myRadio);
//The radio buttons with the same name, form an array
//Only one radio button can be checked at a time
if (theRadioValue.id=="myRadio1")
{
//The code below sets the text for the paragraph
//it is similar for each radio button
para.lastChild.nodeValue = "Oh!
You like JavaScript, do you?";
para.className= "bluey";
}
if (theRadioValue.id=="myRadio2")
{
para.lastChild.nodeValue = "So
you like ice cream!";
para.className= "reddy";
}
if (theRadioValue.id=="myRadio3")
{
para.lastChild.nodeValue = "So
you like to swim!";
para.className= "greeny";
}
}
-->
</script>
|