HTML Radio Button and TypeScript: A Complete Guide

Updated: January 7, 2024 By: Guest Contributor Post a comment

Introduction

Handling HTML radio buttons with TypeScript can greatly improve the structure and type safety of your code. This guide will introduce you to the synergy between HTML radio buttons and TypeScript, providing you with practical and incremental examples.

Getting Started

Firstly, let’s explore how to define a basic HTML radio button:

<form>
  <input type="radio" id="option1" name="choice" value="Option 1">
  <label for="option1">Option 1</label>

  <input type="radio" id="option2" name="choice" value="Option 2">
  <label for="option2">Option 2</label>
</form>

This creates two radio buttons with the same name, indicating they are part of the same group.

Basic TypeScript Integration

To capture the value of the selected radio button with TypeScript, you can write a basic function:

const getSelectedValue = (name: string): string | undefined => {
  const options: NodeListOf<HTMLInputElement> = document.querySelectorAll(`input[name="${name}"]`);
  for (const option of options) {
    if (option.checked) {
      return option.value;
    }
  }
  return undefined;
};

This function looks for all radio inputs with a specified name and returns the value of the selected one.

TypeScript Event Handling

To handle changes to radio button selections, you can add event listeners in TypeScript:

window.addEventListener('load', () => {
  const radios: NodeListOf<HTMLInputElement> = document.querySelectorAll('input[name="choice"]');

  radios.forEach(radio => {
    radio.addEventListener('change', (event) => {
      console.log(getSelectedValue('choice'));
    });
  });
});

These event listeners call the getSelectedValue function whenever a radio button’s state changes.

Enhancing with Enums

Utilize TypeScript enums for more sophisticated handling of radio button values:

enum Choice {
  Option1 = 'Option 1',
  Option2 = 'Option 2'
}

const getSelectedEnum = (name: string): Choice | undefined => {
  const value = getSelectedValue(name);
  return value as Choice;
};

This ensures that the function returns a value contained in the Choice enum, adding an additional layer of type safety.

Integrating with a Component

In the context of a TypeScript framework like Angular:

@Component({
  selector: 'radio-group',
  template: `<form>
    <label>
      <input type="radio" [value]="Choice.Option1" (change)="onChange($event)" [checked]="currentChoice === Choice.Option1"> Option 1
    </label>
    <label>
      <input type="radio" [value]="Choice.Option2" (change)="onChange($event)" [checked]="currentChoice === Choice.Option2"> Option 2
    </label>
  </form>`,
  styles: []
})
export class RadioGroupComponent {
  currentChoice = Choice.Option1;

  onChange(event: Event) {
    this.currentChoice = (event.target as HTMLInputElement).value as Choice;
  }
}

This component binds the radio buttons to a component property, creating a more reusable and maintainable structure.

Advanced Validation

Combining TypeScript with radio buttons allows for advanced form validation patterns, such as:

function isOptionValid(selection: Choice | undefined): boolean {
  switch (selection) {
    case Choice.Option1:
      return true; // Custom logic for Option 1
    case Choice.Option2:
      return false; // Custom logic for Option 2
    default:
      return false;
  }
}

This pattern empowers complex validation rules per radio option, all while preserving type safety.

Summary

Integrating HTML radio buttons with TypeScript elevates the robustness and maintainability of your code, providing a solid foundation for user input handling. By methodically progressing from basic examples to advanced patterns, we’ve demonstrated how TypeScript’s features make for a powerful ally in form processing. Whether you’re working within an existing project or starting fresh, harnessing the capabilities of TypeScript with HTML radio buttons will guide you towards writing better, safer web applications.