Lesson Tuesday

Previously we learned how to gather data from a variety HTML form inputs using jQuery. We delayed learning about checkboxes, since they require a knowledge of arrays. However, now that we have a basic understanding of arrays and looping, let's explore how to retrieve information from commonly-used HTML checkboxes using jQuery.

Transportation Survey

In this lesson we'll build a small website containing a brief survey. Our survey will ask users which methods of transportation they have used to travel to work or school in the past year. For now, the site will simply display a user's responses back to them after the form has been submitted.

As you may already know, checkboxes differ from radio buttons because they allow multiple options to be selected at once, whereas radio buttons are meant for selecting a single option. Since people have likely used more than one mode of transportation in the past year, we'll use checkboxes to collect our survey answers. This will allow users to select all answers that apply to them.

The HTML for this form will look like this:

transportation_survey/index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Transportation Survey</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.1.0.js"></script>
    <script src="js/scripts.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <h2>Transportation Survey</h2>
      </div>
      <form id="transportation_survey">
        <div class="form-group">
          <p>In the past year, I have used the following modes of transportation to travel to work or school:</p>
          <input type="checkbox" name="work-transportation" value="bike"> Riding a bike.<br>
          <input type="checkbox" name="work-transportation" value="car">Driving a car.<br>
          <input type="checkbox" name="work-transportation" value="carpool">Carpooling with others.<br>
          <input type="checkbox" name="work-transportation" value="walk">Walking.<br>
          <input type="checkbox" name="work-transportation" value="bus">Riding the bus.<br>
          <input type="checkbox" name="work-transportation" value="train">Riding the train.<br>
          <input type="checkbox" name="work-transportation" value="streetcar">Riding the streetcar.<br>
          <input type="checkbox" name="work-transportation" value="taxi">Taking a taxi.<br>
          <input type="checkbox" name="work-transportation" value="rideshare">Using a rideshare service like Lyft or Uber.<br>
          <input type="checkbox" name="work-transportation" value="skateboard">Skateboarding.<br>
          <input type="checkbox" name="work-transportation" value="rollerblade">Rollerblading.<br>
          <input type="checkbox" name="work-transportation" value="scooter">Riding a scooter.<br>
          <input type="checkbox" name="work-transportation" value="other">Another mode of transportation not listed here.<br>
        </div>
       <button type="submit">Submit Survey</button>
      </form>
      <span id="work-responses">
        <p><b>You use the following methods of transportation to travel to work or school:</b></p>
      </span>
    </div>
  </body>
</html>

As you can see, we've already linked our Bootstrap and custom stylesheets, jQuery, and our scripts.js files in the <head> tag. Additionally, we've included a <span> below the form with the id work-responses. This will eventually hold our user's responses to our question. When the user first visits our page, the span is hidden with CSS:

transportation_survey/css/styles.css
#work-responses {
  display: none;
}

When the form is submitted, we'll show this span using the .show() jQuery method, and append the user's responses to it. This is the same general process we used to display information gathered from forms throughout last week.

Retrieving Checkbox Values with jQuery

In order to determine which checkboxes the user has selected, we can fetch the form data in our front-end jQuery logic like this:

transportation_survey/js/scripts.js

$(document).ready(function(){
  $("form#transportation_survey").submit(function(event){
    event.preventDefault();
    $("#work-responses").show();
    $("input:checkbox[name=work-transportation]:checked").each(function(){
      var workTransportationMode = $(this).val();
      $('#work-responses').append(workTransportationMode + "<br>");
    });
    $('#transportation_survey').hide();
  });
});

Here, we attach a .submit() listener to our form. When the form is submitted, we display our work_responses <span>.

Then, we use the jQuery selector$("input:checkbox[name=work-transportation]:checked") to target all checkboxes the user has selected. This is a much longer selector than we've previously used. Let's break it down together:

  • The input:checkbox portion of this selector targets <input> fields of the type checkbox.
  • [name=work-transportation] further narrows our search. In addition to targeting only <input> fields of the checkbox type, the name attribute of the field must also be work-transportation.
  • The :checked portion narrows it down even further. In addition to targeting only <input> fields of the checkbox type with a name attribute of work-transportation, we only want to retrieve checked checkboxes that meet these requirements.

Therefore, this selector targets all checkbox inputs with the name attribute work-transportation that the user has checked.

Continuing to walk through the example above, we use an .each() loop to cycle through each checkbox meeting these qualifications. .each() is simply the jQuery-specific version of the JavaScript forEach() loops we've been using this week.

Then, for each checkbox, we determine its value by calling $(this).val();. this refers to the current checkbox being cycled over by the loop. Calling .val() on this retrieves the "value" attribute from that checkbox's HTML. We assign this value to the variable workTransportationMode. Then, we then append this information (and a <br>) to our work-responses span.

Let's give our code a shot! We can select a few modes of transportation, and hit submit:

one-question-checkboxes

And look! It's successfully returning the exact combination of checkboxes we selected when answering our survey question:

one-question-checkboxes-results

Multiple Sets of Checkboxes

Let's say we later wanted to expand our survey to contain two questions: One to ask how people travel to work or school, and another to ask how people travel to other events or activities outside of work and/or school. We want data for each question to come back separately. To achieve this, we would add another set of checkbox inputs that share a different name value:

transportation_survey/index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Transportation Survey</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.1.0.js"></script>
    <script src="js/scripts.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <h2>Transportation Survey</h2>
      </div>
      <form id="transportation_survey">
        <div class="form-group">
          <p>In the past year, I have used the following modes of transportation to travel to work or school:</p>
          <input type="checkbox" name="work-transportation" value="bike"> Riding a bike.<br>
          <input type="checkbox" name="work-transportation" value="car">Driving a car.<br>
          <input type="checkbox" name="work-transportation" value="carpool">Carpooling with others.<br>
          <input type="checkbox" name="work-transportation" value="walk">Walking.<br>
          <input type="checkbox" name="work-transportation" value="bus">Riding the bus.<br>
          <input type="checkbox" name="work-transportation" value="train">Riding the train.<br>
          <input type="checkbox" name="work-transportation" value="streetcar">Riding the streetcar.<br>
          <input type="checkbox" name="work-transportation" value="taxi">Taking a taxi.<br>
          <input type="checkbox" name="work-transportation" value="rideshare">Using a rideshare service like Lyft or Uber.<br>
          <input type="checkbox" name="work-transportation" value="skateboard">Skateboarding.<br>
          <input type="checkbox" name="work-transportation" value="rollerblade">Rollerblading.<br>
          <input type="checkbox" name="work-transportation" value="scooter">Riding a scooter.<br>
          <input type="checkbox" name="work-transportation" value="other">Another mode of transportation not listed here.<br>
        </div>
        <div class="form-group">
          <p>In the past year, I have used the following modes of transportation to travel to other activities and events:</p>
          <input type="checkbox" name="fun-transportation" value="bike"> Riding a bike.<br>
          <input type="checkbox" name="fun-transportation" value="car">Driving a car.<br>
          <input type="checkbox" name="fun-transportation" value="carpool">Carpooling with others.<br>
          <input type="checkbox" name="fun-transportation" value="walk">Walking.<br>
          <input type="checkbox" name="fun-transportation" value="bus">Riding the bus.<br>
          <input type="checkbox" name="fun-transportation" value="train">Riding the train.<br>
          <input type="checkbox" name="fun-transportation" value="streetcar">Riding the streetcar.<br>
          <input type="checkbox" name="fun-transportation" value="taxi">Taking a taxi.<br>
          <input type="checkbox" name="fun-transportation" value="rideshare">Using a rideshare service like Lyft or Uber.<br>
          <input type="checkbox" name="fun-transportation" value="skateboard">Skateboarding.<br>
          <input type="checkbox" name="fun-transportation" value="rollerblade">Rollerblading.<br>
          <input type="checkbox" name="fun-transportation" value="scooter">Riding a scooter.<br>
          <input type="checkbox" name="fun-transportation" value="other">Another mode of transportation not listed here.<br>
        </div>
       <button type="submit">Submit Survey</button>
      </form>
      <span id="work-responses">
        <p><b>You use the following methods of transportation to travel to work or school:</b></p>
      </span>
      <br>
      <span id="fun-responses">
        <p><b>You use the following methods of transportation to travel to other activities and events:</b></p>
      </span>
    </div>
  </body>
</html>

As you can see, the second set of checkboxes all share a fun-transportation name attribute. We've also added an additional <span> to eventually contain the user's responses to this second question. This span is also hidden by CSS, and will be displayed after the form is submitted:

transportation_survey/css/styles.css
#work-responses {
  display: none;
}

#fun-responses {
  display: none;
}

We can gather answers to this question similar to the manner we gathered answers for the first. We add a second loop that targets "input:checkbox[name=fun-transportation]:checked". That is, all checkbox input fields with the name attribute of fun-transportation that are currently checked:

transportation_survey/js/scripts.js
$(document).ready(function(){
  $("form#transportation_survey").submit(function(event){
    event.preventDefault();
    $("#work-responses").show();
    $("input:checkbox[name=work-transportation]:checked").each(function(){
      var workTransportationMode = $(this).val();
      $('#work-responses').append(workTransportationMode + "<br>");
    });
    $("#fun-responses").show();
    $("input:checkbox[name=fun-transportation]:checked").each(function(){
      var funTransportationMode = $(this).val();
      $('#fun-responses').append(funTransportationMode + "<br>");
    });
    $('#transportation_survey').hide();
  });
});

Again, we show the <span> with the id of fun-responses, cycle through each currently-selected checkbox with the name attribute of fun-responses, collect its value, and append it to our span.

We can try this out, too. Let's select a few answers from each of the two questions:

selecting-checkboxes-multiple-questions

After submitting the form we should see each mode of transportation we selected for each question appear on the page:

selecting-checkboxes-multiple-questions-results

Other Uses for Checkbox Data

Do note that you can do far more than simply display a user's responses back to them. The important part here is learning how to target currently-checked checkboxes with jQuery. Once you're able to do this, you could do anything with this information.

For instance, we could set the values of checked boxes aside in an array:

...
  var userResponses = [];
  $("input:checkbox[name=work-transportation]:checked").each(function(){
      var workTransportationMode = $(this).val();
      userResponses.push(workTransportationMode);
    });
...

Or we could manipulate this data in whatever fashion we please:

...
  $("input:checkbox[name=work-transportation]:checked").each(function(){
      var workTransportationMode = $(this).val();
      var capitalWorkTransportationMode = workTransportationMode.toUpperCase();
      ...
    });
...

Examples


If we had the following form containing a group of checkboxes:

transportation_survey/index.html
<!DOCTYPE html>
<html>
  <head>
    <title>Transportation Survey</title>
    <link href="css/bootstrap.css" rel="stylesheet" type="text/css">
    <link href="css/styles.css" rel="stylesheet" type="text/css">
    <script src="js/jquery-3.1.0.js"></script>
    <script src="js/scripts.js"></script>
  </head>
  <body>
    <div class="container">
      <div class="jumbotron">
        <h2>Transportation Survey</h2>
      </div>
      <form id="transportation_survey">
        <div class="form-group">
          <p>In the past year, I have used the following modes of transportation to travel to work or school:</p>
          <input type="checkbox" name="work-transportation" value="bike"> Riding a bike.<br>
          <input type="checkbox" name="work-transportation" value="car">Driving a car.<br>
          <input type="checkbox" name="work-transportation" value="carpool">Carpooling with others.<br>
          <input type="checkbox" name="work-transportation" value="walk">Walking.<br>
          <input type="checkbox" name="work-transportation" value="bus">Riding the bus.<br>
          <input type="checkbox" name="work-transportation" value="train">Riding the train.<br>
          <input type="checkbox" name="work-transportation" value="streetcar">Riding the streetcar.<br>
          <input type="checkbox" name="work-transportation" value="taxi">Taking a taxi.<br>
          <input type="checkbox" name="work-transportation" value="rideshare">Using a rideshare service like Lyft or Uber.<br>
          <input type="checkbox" name="work-transportation" value="skateboard">Skateboarding.<br>
          <input type="checkbox" name="work-transportation" value="rollerblade">Rollerblading.<br>
          <input type="checkbox" name="work-transportation" value="scooter">Riding a scooter.<br>
          <input type="checkbox" name="work-transportation" value="other">Another mode of transportation not listed here.<br>
        </div>
       <button type="submit">Submit Survey</button>
      </form>
      <span id="work-responses">
        <p><b>You use the following methods of transportation to travel to work or school:</b></p>
      </span>
    </div>
  </body>
</html>

This jQuery would retrieve all selected checkboxes, and append their values to a span in our HTML:

transportation_survey/js/scripts.js

$(document).ready(function(){
  $("form#transportation_survey").submit(function(event){
    event.preventDefault();
    $("#work-responses").show();
    $("input:checkbox[name=work-transportation]:checked").each(function(){
      var workTransportationMode = $(this).val();
      $('#work-responses').append(workTransportationMode + "<br>");
    });
    $('#transportation_survey').hide();
  });
});

  • The input:checkbox portion of this selector targets <input> fields of the type checkbox.
  • [name=work-transportation] further narrows our search. In addition to targeting only <input> fields of the checkbox type, the name attribute of the field must also be work-transportation.
  • The :checked portion narrows it down even further. In addition to targeting only <input> fields of the checkbox type with a name attribute of work-transportation, we only want to retrieve checked checkboxes that meet these requirements.