JavaScript with Forms


Now that you know how JavaScript variables and functions work and how HTML forms work, its time to learn how to put them together. First lets create a radio button, but this time we will do it a bit differently. For JavaScript to be able to use a radio button, it must be able to distinguish that specific radio button from all the others you might have put on your page. This is done by giving the radio button a name:

<form name="form1">
<input type="radio" name="radio1">
</form>

Now JavaScript can identify this radio button. It is the radio button called radio1 in the form called form1. In JavaScript the radio button would be known as "form1.radio1" since its in form1 and its called radio1.

Now that we have a radio button with a name, we have to give it a JavaScript function so that it can actually do something:

<form name="form1">
<input type="radio" name="radio1" onClick="my_function()">
</form>

onClick simply states that when ever that radio button is clicked it will call the JavaScript function called my_function(). Lets create my_function().

<Script language="JavaScript">
function my_function(){
form1.radio1.checked=true;
}
</Script>

This function will make the radio button get marked. Here is an example of a working radio button (using the same code from above):

Now lets put multiple radio buttons together and make it so that when one is clicked it gets marked but the others get unmarked. Here is how it is done:

<form name="form1">
<input type="radio" name="radio1" onClick="form1_radio1()">
<input type="radio" name="radio2" onClick="form1_radio2()">
</form>

<Script language="JavaScript">
function form1_radio1(){
form1.radio1.checked=true;
form1.radio2.checked=false;
}
function form1_radio2(){
form1.radio1.checked=false;
form1.radio2.checked=true;
}
</Script>

This function will mark it if it is unmarked and unmark it if it is marked. This way the person taking your quiz can only mark one answer per question.

Back to Main Page 1