Checkbox Tutorial

Step 1

The most basic checkbox.

We use the <input> element, and specify its type attribute to be checkbox.

There is no <checkbox> element.

Output

Step 2

Now let's attach a value to our checkbox.

We do this with the value attribute.

Output

Step 3

Now let's make that value visible.

We do this with the <label> element.


Output

Step 4

Now let's associate our label with our checkbox.

This way, clicking the label will check our checkbox.

We do this by adding a for attribute to our label...

That corresponds to the id attribute of our checkbox.


Output

Step 5

Let's add more checkboxes!

We can chose which checkbox is 'pre-chosen' with the checked attribute.






Output

Step 6

Now let's group our checkboxes together.

We do this with the name attribute.

We'll need this when we retrieve the chosen checkbox.






Output

Step 7

Now let's retrieve the value of the chosen checkbox!

We do this by targeting the name attribute of our checkbox, and applying the :checked jQuery selector.

Note that when more than one checkbox is checked, we receive an array from our retrieval, and we iterate through that array.

$('.btn--cb4').on('click', function() {
  var arrCB = [];
  $('input[name="cb4"]:checked').each(function(index, el) {
    arrCB.push(el.value);
  });
  $('.cb4-value').text(arrCB.join(', '));
});

Output

Value(s) from cb4 group: