How to set attribute for checkbox field I want to add the attribute data-toggle="toggle" to a checkbox field. 

I thought I could use the hook theme_checkbox which is:

function theme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' =&gt; 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }
  _form_set_class($element, array('form-checkbox'));

  return '&lt;input' . drupal_attributes($element ['#attributes']) . ' /&gt;';
}


So I customised it to:

function mytheme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' =&gt; 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }

  //*******Added 3 lines below*******
  if ($element['#attributes']['id'] = 'edit-profile-carer-field-profile-active-und') {
      element_set_attributes($element, array('#attributes' =&gt; 'data-toggle="toggle"'));
  }

  _form_set_class($element, array('form-checkbox'));

  return '&lt;input' . drupal_attributes($element ['#attributes']) . ' /&gt;';
}


However, instead of just adding the attribute data-toggle="toggle" to the checkbox field  with the id edit-profile-carer-field-profile-active-und, it is adding the attribute to all the checkboxes on the form.

Can someone tell me what I am doing wrong? How can I target just the the checkbox I want? Or do I need to use another approach to do it?
I'd recommend you do this via a form alter.  But that aside, the reason your code doesn't work is that you're not doing your comparison correctly.

if ($element['#attributes']['id'] = 'edit-profile-carer-field-profile-active-und') {


Should be:

if ($element['#attributes']['id'] == 'edit-profile-carer-field-profile-active-und') {


And you're also not setting the attribute correctly.  So the final function should be:

function mytheme_checkbox($variables) {
  $element = $variables ['element'];
  $element ['#attributes']['type'] = 'checkbox';
  element_set_attributes($element, array('id', 'name', '#return_value' =&gt; 'value'));

  // Unchecked checkbox has #value of integer 0.
  if (!empty($element ['#checked'])) {
    $element ['#attributes']['checked'] = 'checked';
  }

  //*******Added 3 lines below*******
  if ($element['#attributes']['id'] == 'edit-profile-carer-field-profile-active-und') {
      $element['#attributes']['data-toggle'] = 'toggle';
  }

  _form_set_class($element, array('form-checkbox'));

  return '&lt;input' . drupal_attributes($element ['#attributes']) . ' /&gt;';
}