1

How do I target the currently selected radio button with javascript? I do have a script to know which radio is currently selected. How ever, I wanted to do something else after I figured out which is currently selected.

var selectedRadio = document.getElementById('changeDetails').value; if (selectedRadio == 'options1') { //do something to radio button with value options1 }

How would I be able to target the currently selected radio if I only have the value of it as an identifier? I'm thinking of something like getElementByValue but of course, that doesn't exist so I'm looking for something that does the same.

No jQuery.

GibiDroidZ
  • 120
  • 1
  • 13

1 Answers1

2

IDs are unique. You have ONE radio with ID changeDetails and value options1

That said - use the name and :checked, assuming the radios have a name as they are supposed to

var checkedRad = document.querySelector('input[name=changeDetails]:checked');

or

var val = "option1";
var radByVal = document.querySelector('input[value='+val+']');
if (radByVal.checked) { ... }
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Thanks to this code! I somehow modified it so I could target the element that I want. I want to target the element with a value equal to the currently selected radiobutton. Since the way how elements work is somehow complicated, it doesn't return a value with your code but I used this instead document.querySelector('input[value=group1]') – GibiDroidZ Aug 07 '17 at 02:03