Hide one form element until another is selected
As @leymannx stated you can achieve this using #states. Here is a simple example:



 $form['show_textbox'] = array(
  '#type' =&gt; 'checkbox',
  '#title' =&gt; t('Show text Box 1'),
        '#attributes' =&gt; [
        'id' =&gt; 'show_textbox',
        'name' =&gt; 'field_show_textbox',
      ],
);

    $form['text_box1'] = [
      '#type' =&gt; 'textfield',
      '#size' =&gt; '60',
      '#placeholder' =&gt; 'Enter Name',
      '#attributes' =&gt; [
        'id' =&gt; 'text_box1',
        'autocorrect' =&gt; 'none',
        'class' =&gt; 'text_box1',
        'autocapitalize' =&gt; 'none',
        'spellcheck' =&gt; 'false',
      ],
      '#states' =&gt; [
        //show this textfield only if the radio button 'show_textbox1' is selected
        'visible' =&gt; [
                ':input[name="field_show_textbox"]' =&gt; array('checked' =&gt; TRUE),
        ],
      ],
    ];



You can always change the condition.