I have a webform with a set of radio buttons (group).

I need to conditionnaly select one of the radio buttons based on the value of another field. I thought I would use Javascript to achieve this task.

The radio group is set to be required.

Visually, the radio button gets selected as expected, but when I submit the form, I get and error that says "Field my-radio-field is required". And the webform is displayed below the message and I can see that my radio field has no option selected.

Here is my Javascript for reference:

Drupal.behaviors.installationForm = {

  attach: function(context) {

    once('installation-form', '.webform-submission-installation-form', context).forEach(function(element) {

      // On field change
      $('input[name="drivers_installation"]', element).on('change', function() {
        // Condition
        if ($('#edit-drivers-installation-server', context).is(':checked')) {

          // Select radio button
          $('#edit-my-radio-field', context).prop('checked', true);

I must be missing something. What is the correct way of selecting a webform radio button with Javascript?

  • You should attempt this using #states, most likely.
    – Kevin
    Jun 14 at 14:54
  • @Kevin From the docs: Drupal's Form API #states property allows to easily show or hide, enable or disable, require or collapse form fields based on values selected or entered in other fields on that form or anywhere else on the page.
    – MrUpsidown
    Jun 14 at 21:20
  • Changing the focus on a form element when users are changing the value of a different form element is bad user experience; that's probably why Drupal JavaScript states don't allow that. Instead, I would keep that form element hidden and show it when the other form element contains a specific value. This is something the Drupal JavaScript states make possible.
    – apaderno
    Jun 15 at 8:30
  • @apaderno I can't think of why it would be bad UX to force select a specific radio button based on another field value. I have 2 sets of radio buttons, if option 1 is selected on the first set, both options are available in the second set. If option 2 is selected, the second set of radios gets disabled, with one option selected (forced). All I want to achieve is that when option 2 is selected, the user does not have the possibility to choose the option from second set. Even though it might be bad UX, it doesn't explain why I get the behavior I described in my question.
    – MrUpsidown
    Jun 15 at 8:54
  • That said, I will think of a workaround as you suggested, maybe I can just hide that field when option 2 is selected on the first set, and show a markup field with a descriptive text instead of the force-selected radio. I'd still be happy if I would understand how I could do it...
    – MrUpsidown
    Jun 15 at 8:56


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.