Fork me on GitHub

We can either create a single checkbox, or multiple checkboxes for our users. Also checkout the Checkbox Widget page.

Single Checkbox

When creating a form, we can add a single checkbox to it:

Checkbox Element

Form Element

form.elements['my_checkbox'] = {
  title: 'Enjoy Pizza?',
  type: 'checkbox',
  description: 'Check this box if you enjoy pizza.',
  default_value:1 /* a value of 1 checks the box */
};

Unlike other form inputs in jQuery Mobile, a checkbox needs a label associated with it to automatically be rendered in a "mobile" way. The DrupalGap Forms API takes care of the label for us, but if we wish to use a Render Object or the theme() function, then we need to create a label for the checkbox as well.

Multiple Checkboxes

Alternatively, when creating a form we can also provide multiple checkboxes that are grouped together:

Multiple Checkboxes Element

Form Element

form.elements['my_pizza_toppings'] = {
  title: 'Pizza Toppings',
  type: 'checkboxes',
  required: true,
  options: {
    ham: 'Ham',
    pineapple: 'Pineapple',
    bacon: 'Bacon'
  }
};

Checking Multiple Checkboxes

Use the option key(s) as the key value pairs on default_value to have the boxes be checked by default:

default_value: {
  ham: 'ham',
  pineapple: 'pineapple',
}

Dynamically Injecting Checkboxes

Often times we may want to use a pageshow handler to call the Drupal server for some data, then use that data to build a dynamic set of checkboxes. Here's a simple example which appends a checkbox to a checkboxes element on a form:

$('.field-name-my-checkboxes').append(
  '<label>' + theme('checkbox', {
      value: 'foo',
      attributes: {
        name: 'my_checkboxes[foo]',
        'class': 'my_checkboxes',
        value: 'foo'
      }
  }) + ' foo</label>'
).trigger('create');

Just be careful with utilizing the CSS selector, and the name and value attributes, all must utilize the values generated by the DrupalGap Forms API so the submission handler can pick them up properly. When in doubt, just place a dummy option on your checkboxes element in your form builder, then inspect the HTML to see what values to use.