skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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:

    let readStatus;
    
    if (readStatusInput) {
        readStatus = readStatusInput.value;
    } else {
        // Handle the case where no radio input is checked
        readStatus = null; // Or any other default value you want to assign
    }
    
    console.log(readStatus);
    1.
     We first retrieve the checked radio input element using `document.querySelector('input[type="radio"]:checked')` and store it in the readStatusInput variable.
    2.
    Then, we check if `readStatusInput` is not `null` (i.e., if there is a checked radio input).
    3.
    If there is a checked radio input, we assign its `value` property to the `readStatus` variable.
    4.
    If there is no checked radio input, we can handle this case accordingly. In this example, we assign `null` to the `readStatus` variable, but you can choose any other default value or perform any other actions you need.
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search