-1

I created an admin page where I input values of similar type='name' which will pop up on submit to another page as radio buttons. But I'm getting an error 'cannot read property value of null' from the console on the page where the radio buttons are been posted.

let answer = document.querySelector('input[name="choice"]:checked').value;
probitaille
  • 1,899
  • 1
  • 19
  • 37
  • Why are you doing it with a query selector like this? The whole point of a radio button is that multiple radios with the same name take on a single value; so for instance, if the radio is in a form named `testForm`, you could just do `document.testForm.choice.value` to get the currently checked value. No query selector needed. – IceMetalPunk Oct 11 '19 at 19:17
  • @IceMetalPunk If the `querySelector` returns null, your approach won't work as well... – FZs Oct 11 '19 at 19:24
  • Maybe, though there might be a reason the query selector is returning null that won't break the usual named approach. Hard to tell without seeing the HTML. (It might just be that none of the radio options are checked yet, in which case the named approach at least won't throw any errors.) – IceMetalPunk Oct 11 '19 at 19:57
  • Possible duplicate of [How to get value of selected radio button?](https://stackoverflow.com/questions/15839169/how-to-get-value-of-selected-radio-button) – Ilan Schemoul Oct 11 '19 at 21:24

2 Answers2

0

var radios = document.getElementsByName('genderS');

for (var i = 0, length = radios.length; i < length; i++) {
    if (radios[i].checked) {
        // do whatever you want with the checked radio
        alert(radios[i].value);

        // only one radio can be logically checked, don't check the rest
        break;
    }
}
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked="checked">Male</input>
<input type="radio" name="genderS" value="0" >Female</input>
Khalil
  • 136
  • 1
  • 6
0

The snippet that you provided should work. It does assume that there are input fields in HTML that:

  1. have name="choice", and
  2. has been checked

Without seeing the HTML, it's hard to say, but maybe look for a typo in the HTML.

document.getElementById('button').addEventListener('click', () => {
  const radio = document.querySelector('input[name="choice"]:checked');
  if (radio) {
    const answer = radio.value;
    console.log(`choice ${answer}`);
  } else {
    console.log('no choice');
  }
});
<label><input type="radio" name="choice" value="1" /> One</label>
<label><input type="radio" name="choice" value="2" /> Two</label>
<div>
  <button id="button">Click</button>
</div>
Soc
  • 7,425
  • 4
  • 13
  • 30