Setting radio button values in a Drupal ajax call

On a recent Drupal project we had a form that was acted upon via an ajax call, and we needed to set the values of some radio buttons to their default state.

We weren't actually submitting the form using a $form['submit'] element, so rebuilding the form after clicking 'Submit' wasn't resetting the radio buttons.

The ajax_command_invoke() function makes this sort of thing possible, and it's pretty easy with some field types. Best way to construct your ajax_command_invoke command is to work in the console using jquery selectors to identify the element you're trying to change and to structure the jquery action to change that element.

Some fields are pretty straightforward, as in the case of setting a text field to have empty contents. For example if your text field's id is "#my-element-id", your console query $("#my-element-id") will return that field, and $("#my-element-id").val("") will set its value to be empty. 

In the language of an ajax_command_invoke command, this would translate to:

$commands[] = ajax_command_invoke('#my-element-id', 'val', array(""));

The radio button field type is a little more complicated - until one realizes that the $arguments array can contain arrays of arguments.

In the console, then, if we can de-select a radio button using $("#my-radio-button-id").prop('checked', FALSE), the Drupal ajax command is:

$commands[] = ajax_command_invoke('#my-radio-button-id', 'val', array(array('checked' => FALSE)));