Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get the value of checked radio button

I am trying to make a form that is reactive to what a user inputs. I have a list of radio buttons, and for now, I just want to log the value of whatever button is selected in the console (I will implement more logic later). I know I will need some sort of event listener to log the value if a user changes their selection as well.

I am still learning so any explanation with answers is greatly appreciated.

Here is an example of what I have now.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<input type='radio' value='value1' name='example' id='value1'>
<label for='value1'>Value 1</label>
<input type='radio' value='value2' name='example' id='value2'>
<label for='value2'>Value 2</label>
<input type='radio' value='value3' name='example' id='value3'>
<label for='value3'>Value 3</label>
let valueName = document.querySelector('input[name="example"]:checked').value;

When I log valueName to the console. I get a TypeError: Cannot read properties of null (reading ‘value’.

Im not sure where to go from here.

>Solution :

The reason for your error is because the selector you have specified IS NULL at the point that the code runs.

If you’re doing document.querySelector('input[name="example"]:checked').value onload, then the selector doesn’t exist because there is no input with name="example" which has the checked attribute. There is however three input elements with name="example" but that isn’t what you’re telling the JavaScript to select.

To make this function as you intend, then you need to use an event listener as you correctly assumed in your question.

// Select all inputs with name="example"
var radios = document.querySelectorAll("input[name=\"example\"]");

// Use Array.forEach to add an event listener to each radio element.
radios.forEach(function(radio) {
  radio.addEventListener('change', function() {
    let valueName = document.querySelector('input[name="example"]:checked').value;
    console.log(valueName)
  })
});
<input type='radio' value='value1' name='example' id='value1'>
<label for='value1'>Value 1</label>
<input type='radio' value='value2' name='example' id='value2'>
<label for='value2'>Value 2</label>
<input type='radio' value='value3' name='example' id='value3'>
<label for='value3'>Value 3</label>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading