Home
| Colors: |

HTML Radio Button Input Type Element Example

October 2024

Output

Example Switch

HTML

<fieldset>
  <legend>Example Switch</legend>
  <div>
    <input 
      type="radio" 
      id="switch_is_on" 
      name="example_switch" 
      value="on" 
      checked />
    <label for="switch_is_on">On</label>
  </div>
  <div>
    <input 
      type="radio" 
      id="switch_is_off" 
      name="example_switch" 
      value="off" />
    <label for="switch_is_off">Off</label>
  </div>
</fieldset>

Example Script

JavaScript
function logSwitchState(event) {
  let el = event.target
  console.log(`Switch is now ${el.value}`)
}

document.addEventListener("DOMContentLoaded", () => {
  const buttons = 
    document.querySelectorAll('input[name="example_switch"]')
  buttons.forEach((btn) => {
    btn.addEventListener(
      "input", 
      logSwitchState
    )
  })
})
end of line