I’m working on a form with radio input that has values "yes" and "no".
Here’s the code:
<input type="radio" id="haveread" name="check" value="yes"><label for='haveread' >Yes</label>
<input type="radio" id="notread" name="check" value="no"><label for="notread" >No</label>
I’d like to retrieve the radio input value of the radio that has been checked and assign it to variable called readStatus
Here’s my code:
const readStatus = document.querySelector('input[type="radio"]:checked');
I tried checking the variable readStatus on my console.log and it returns null.
However, when i input document.querySelector(‘input[type="radio"]:checked’ on the console.log, which is the content of the variable readStatus, i get what I’m looking for which is the checked radio input.
i am expecting the variable readStatus to also return the checked radio input. I’m very confused as to how this works because I’m basically console.logging the same thing.
Can anyone tell me what I’m doing wrong ?
Edit:
Here’s a screenshot of the project, and the console.log
project screenshot and console
2
Answers
it comes down to a few couple of things. so first of all, when are you grabbing the value with the querySelector ? at page ready time ? on an event with an event handler ? so the value changes on the radio button when you select one of the options. thus, you need to add an event listener to the radio buttons that fires when you select an option. in said even handler you can set you readStatus var with the value you grab at that point with the query selector.
I would suggest maybe having a look here for some information and examples on event listeners.
The issue here is that document.querySelector(‘input[type="radio"]:checked’) returns the checked radio input element itself, not its value. To retrieve the value of the checked radio input, you need to access its value property.
Here’s how you can fix your code: