skip to Main Content

When trying to console log a variable I declared inside of my event function, my console is shooting back this error

Uncaught TypeError: Cannot read properties of null (reading 'value')
    at HTMLButtonElement.wuTangForever (main.js:16:76)

I tried to make a form, with radio inputs and attributes.

<p>Pepsi or Coke?</p>
<input type="radio" id="pepsi" name="soda" value="1">
<label for="">Pepsi</label>
<input type="radio" id="coke" name="soda" value="2">
<label for="">Coke</label>

In my JavaScript, I have the following code:

const sodas = Number(document.querySelector('input[name = soda]:checked').value)

when I console.log(sodas), or do anything, the message error appears. I checked my script tag as I saw others were having the same issue. That did not resolve the issue.

What I want to do is get the value of the checked radio input, turn that value into a number to put into an array.

2

Answers


  1. querySelector potentially returns null if no matches are found, so your code should handle that case. This looks to be the case if no radio option is selected just yet.

    Using the Optional Chaining operator may likely be enough. It checks if the value being chained from is null or undefined and safely accesses the property.

    const sodas = Number(
      document.querySelector('input[name = soda]:checked')?.value
    );
    

    You may also consider assigning one of the options as a default already selected.

    Examples:

    <p>Pepsi or Coke?</p>
    <label>
      <input type="radio" id="pepsi" name="soda" value="1" checked="true">
      Pepsi
    </label>
    <label>
      <input type="radio" id="coke" name="soda" value="2">
      Coke
    </label>
    
    <p>Pepsi or Coke?</p>
    <label>
      <input type="radio" id="pepsi" name="soda" value="1" checked>
      Pepsi
    </label>
    <label>
      <input type="radio" id="coke" name="soda" value="2">
      Coke
    </label>
    
    Login or Signup to reply.
  2. Just use "?", so if there’s value it will return otherwise you will not get null value error.

    const sodas = Number(document.querySelector('input[name = soda]:checked')?.value);
    console.log(sodas);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search