Radio Button OnClick Event Handling in JavaScript

The original tutorial calls these “period buttons”; in HTML they are radio buttons. Clicking a radio button can run JavaScript, update the URL, or submit a form. The original male/female query-string demo and Submit control are preserved.

Demo of the onclick event of radio button

Table of Contents

Read the Selected Radio Value Top ↑

const selected = document.querySelector('input[name="type"]:checked');
if (selected) {
  console.log(selected.value);
}

This avoids looping over every radio control just to find the checked item.

Reload the Page with the Selected Value Top ↑

function reloadWithType(value) {
  const url = new URL(window.location.href);
  url.searchParams.set('type', value);
  window.location.href = url.toString();
}

Submit a Form Automatically on Click Top ↑

If selecting a radio option should immediately submit the form, listen for change or click and call requestSubmit(). Keep an explicit Submit button when users may prefer to review before submission.

radio.addEventListener('change', () => {
  form.requestSubmit();
});

Complete Query-String Demo Source Top ↑

<form name="form1" method="post" action="" id="typeForm">
  <input type="radio" name="type" value="male"> Male
  <input type="radio" name="type" value="female"> Female
  <input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('typeForm');
form.querySelectorAll('input[name="type"]').forEach((radio) => {
  radio.addEventListener('click', () => {
    const url = new URL(window.location.href);
    url.searchParams.set('type', radio.value);
    window.location.href = url.toString();
  });
});
</script>

Event Handling onMouseOver and onMouseOut




Subscribe to our YouTube Channel here



plus2net.com







alex

03-03-2012

Good article, helped a lot. Thanks



✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer