How do I use hook_form_alter() to add CSS classes to a custom input field in user_register_form? I want to add a CSS class to the input element of a custom field in my user_register_form.

This is the field markup.

&lt;div class="field-type-text field-name-field-personal-best field-widget-text-textfield form-wrapper"
 id="edit-field-personal-best"&gt;
&lt;div id="field-personal-best-add-more-wrapper"&gt;
    &lt;div class="form-item form-type-textfield form-item-field-personal-best-und-0-value"&gt;
        &lt;label for="edit-field-personal-best-und-0-value"&gt;Personal Best &lt;/label&gt;
        &lt;input class="text-full form-text" id="edit-field-personal-best-und-0-value"
               name="field_personal_best[und][0][value]" value="" size="60" maxlength="255" type="text"&gt;
    &lt;/div&gt;
&lt;/div&gt;




This is my implementation of hook_form_alter(), which doesn't work. Changing the submit button works, but adding a CSS class to that input element doesn't.

function em_form_alter(&amp;$form, &amp;$form_state, $form_id) {    
if ($form_id == 'user_register_form') {
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['edit-field-personal-best']['#attributes']['class'][] = 'timepicker hasDatepicker';
}}


How can I achieve this?
Looks like you're trying to use the HTML ID of the element you're interested in as the identifier in PHP - not quite how it works.

For a field API field, that will look more like:

$form['field_personal_best'][LANGUAGE_NONE][0]['value']['#attributes']['class'][] = 'foo';


Your mileage will probably vary there, have a read of Why is hook_form_alter() so messy? for some relevant information, and make sure you have the Devel module installed to help with debugging (dpm($form) will tell you pretty much everything you need to know).