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
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.
You may also consider assigning one of the options as a default already selected.
Examples:
Just use "?", so if there’s value it will return otherwise you will not get null value error.