Radio Choices

by Charlie Calvert

Get Started

As we have done in the past, I want you to begin by creating two files in your javascript-test directory

The next steps should also be familiar:

And finally, flesh out the structure of your HTML file with these tags and directives:

Here is a suggested look and feel for the small page that we are going to build. I show it to you so you can get a sense of where we are headed.

Radio Choice UI

Add Main Sections

Inside your main element create two section elements. In the first, put this code:

    <legend>The User Selection</legend> 
    <p><b>User choice</b>: <span id="user-choice">Unknown</span></p> 

Inside the next section element, put this code:

        <legend>Our Form</legend>
        <!-- OUR FORM GOES HERE -->


The section tag that wraps your form fieldset should have an ID of form-section. This ID is used in the set-color function shown later in this document. Be sure to include this ID or your code won't work. (Just to be clear, I'm asking you to add the section elements that wrap the above code. The second section should have the ID. This is a simple task, but I want you to do it.)

Create Form

Previously, we have responded to simple button clicks with onclick events. This time we will look at an alternative way to respond to button clicks. In this model, we will create an HTML element called a form, and place a submit button in the form. This is a common model in web development, especially when one wants to send data back to a server. We will not use a server, but we will learn at least the client side of one way to handle the client/server model in web apps.


Create a form with two radio buttons and a submit button.

<form id="sort-type" action="goThere">
    <input type="radio" id="blue" name="sorter" value="Blue" checked>
    <label for="blue">Blue</label>

    <input type="radio" id="green" name="sorter" value="Green">
    <label for="green">Green</label>
    <input class="btn-padding" type="submit" value="Submit">

Here we create a form with an ID of sort-type. Inside it we place two radio buttons. Note that both radio buttons have the same type and the same name. The name attribute is used to bind the two radio buttons together so that they act as a single unit. If you select one, then the second is deselected. This way only one radio button can be chosen at a time. We also use the ID of the radio button to link it to the label. That way, clicks on the label are the same as clicks on the radio button itself.

We have only two radio buttons, but you can add as many to this group as you want. If you want to create a second set of radio buttons, then simply give the second set a different name and they too will act together as a unit without affecting the first group. (Just to be clear, I'm not asking you create a second set of radio buttons in this exercise.)

Note that we add an empty attribute called checked to one radio button. This is our way of telling the HTML file that we want this button to be selected by default. It is always a good idea to have one default option selected on your radio buttons. Otherwise, when events are fired, no particular option will be selected, and your code might produce random and non-sensical results.

NOTE: Think of it this way. Suppose we said "When the bell rings, go out the back door if the light is red and the front door if the light is green." Then we ring the bell without turning on either the red or green light. The result is likely to be chaos. The same thing can happen in an application if you don't set default values for your radio buttons.

Finally, notice that we have a submit button beneath the radio buttons. Somewhat confusingly, we use the input control to create this button. Confusing or not, it is an old, established tradition in web development and one that you need to understand if you want to do any real work in the web development world.

When the user clicks on the submit button an event is fired, just as onclick events are fired by the buttons we have created in previous projects. Our goal will be to respond to these events, and act appropriately when they fire.

Responding to Form Submit Events

When we click on a button or select a radio button, we generate events. A message is sent out to announce the event. We can write JavaScript code that listens for these events, and takes specific actions when they occur. We have done this several times already by responding to onclick events.

In this app we will respond to submit button clicks. Radio buttons also send out events, but we will not respond to them. At least not at first. Instead, when a submit button is clicked, we will use a JavaScript method to query the radio buttons as to their current state.

Here is the code for responding to events generated by the submit button for our simple form.

const myForm = document.getElementById('sort-type');

myForm.addEventListener('submit', (event) => {
    const value = document.querySelector('input[name="sorter"]:checked').value;
    if (value.toLowerCase() === 'green') {
    } else {

let currentClass = null;

const setColor = (className) => {
    console.log("SET CLASS TO", className);
    var element = document.getElementById("form-section");
    if (currentClass) {
    currentClass = className;

To make this work, we also need to add two CSS rules:

.blueBackground {
    background-color: aqua;

.greenBackground {
    background-color: green;

Here is a break down of the code:

All that is good and well. The trickiest part comes next. We want to find out which radio button was selected when the user clicked the select button. We do this by creating a very fancy selector.

Pause for a moment, and look at the getElementById call. We pass sort-type as a parameter to that method. The ID sort-type is called a selector. When we call querySelector, we are doing the same thing, only our selector is much fancier.

The selector for our calls to getElementById has one part: the ID of the control we want to access. This selector has three parts:

Put it all together and you get our selector:


If you look back at our code, you will see that we then ask for the value of our selected radio button. This value uniquely identifies the radio button that was selected and gives us enough information to act on the user's choice. If necessary, go back to the original declaration for our radio buttons on the HTML form, and not that we gave them unique, and descriptive value attributes.

Admittedly, this process is a bit complex, perhaps too complex for this course. Nevertheless, it is an excellent example of the way developers use simple logic to perform powerful actions. If you continue to pursue your interest in programming, you will find tasks like this become simpler over time because you perform similar actions so frequently. It is a bit like learning to ride a bike: at first it is hard, then later you may find it difficult to understand how anyone does not know how to such things.

The difference between getElementById and querySelector is simple: "If you know the ID (which must be unique) of an element, then use getElementById, but if there is no ID to use, then querySelector is a more generic solution.

There is also querySelectorAll, which returns not the first element that matches the selector, but all that match it.

See also:


There is, of course, one final section in the code block we have been studying.

if (value.toLowerCase() === 'green') {
} else {

In this code, we make a decision based on which of the two radio buttons the user chose. In our program, we then simply display our output in the span of the paragraph element with the ID user-choice and set the background color of the form section. I give you the setColor method but ask you to create the simple showChoice method. Put the showChoice method outside the window.onload block. I'll leave it up to you to implement it since we have already many times made calls to getElementById and then use the textContent property.

If you select the Blue option and press the button, the background of the form should change to blue. I give you a method called setColor that swaps the HTML class associated with the form. We use the class to set the background-color for the form. Thus, if we change the class for the form, we change the color of the form. The trick is to know how to change the class for a form on the fly. If you study the code for setColor it should soon be clear how it is done.

First we use getElementById to select the section of the HTML document that we want to change. Then we use the classList.add and classList.remove methods to swap the in a new class for the section. We also use the old programmer's trick of saving the currentClass in a variable so we know what class to swap out before swapping in the new one.

The images shown below demonstrate how the class on the section element is changed when the user clicks the submit button and different options are chosen.

Radio choices in chrome Radio choices in Firefox

Look on for more tips on working with if and else. These will be useful if you are struggling with this part of the assignment.

Turn it in

Your final application should have five radio buttons:

NOTE: I don't really care which colors you choose, so if you want to come up with your own color schemes then proceed apace.

When the user clicks the button, make sure your code displays the value of the selected radio button in our span and changes the background color of the form.

This exercise has two primary goals:

  1. To ensure you understand how to create radio buttons
  2. To ensure that you can compose a relative complex if..else clause.

When you are done, commit and push your work. Tell me the name of the files you created when you submit your work and provide a link to your code running on GitHub Pages. The link should be to your home page, and your home page should link to implementation of this exercise.

Look and Feel