There are few different ways we can check that based on you have a single radio button or multiple.

Input Radio checked Property

The checked property sets or returns the checked state of a radio button.

This property reflects the HTML checked attribute.

It is supported in all major browsers.

Syntax


radioId.checked

// not necessarily only Id though

Set the checked property:


radioId.checked = true or false (default is false)

// not necessarily only Id though

Where true| or false specifies whether a radio button should be checked or not. true means the radio button is checked and false means the radio button is not checked.

Examples

Find out if a radio button is checked or not:


var x = document.getElementById("testRadioButton").checked;

What to do when you have more than one radio buttons?

Use a for loop to go through each one of them and find out which one is checked


<!-- HTML --> 

<form action="/action_page.php">
  <input type="radio" name="coffee" value="cream">With cream<br>
  <input type="radio" name="coffee" value="sugar">With sugar<br>
  <br>
  <input type="button" onclick="myFunction()" value="Send order">
  <br><br>
  <input type="text" id="order" size="50">
  <input type="submit" value="Submit">
</form>

//JS

function myFunction() {
  var coffee = document.forms[0];
  var txt = "";
  var i;
  for (i = 0; i < coffee.length; i++) {
    if (coffee[i].checked) {
      txt = txt + coffee[i].value + " ";
    }
  }
  document.getElementById("order").value = "You ordered a coffee with: " + txt;
}

One more for loop example for multiple radio buttons


<!-- HTML -->

<form>
  <input type="radio" name="coffee" value="cream">With cream<br> 
  <input type="radio" name="coffee" value="sugar">With sugar<br>
  <input type="button" id="btn" value="Show User Preferences">
</form>

// JS

const btn = document.querySelector("#btn");

btn.onclick = function () {
  const selections = document.querySelectorAll('input[name="coffee"]');
  let userSelection;
  for (const selection of selections) {
    if (selection.checked) {
      userSelection = selection.value;
      break;
    }
  }
  console.log(userSelection);
};

0 Comments

Leave a reply

Your email address will not be published. required fields are marked *