Carla
Carla

Reputation: 13

how to get acess to the input value that is selected

I'm getting this error

error:Uncaught TypeError: Cannot read properties of null (reading 'value')
    at HTMLButtonElement.<anonymous> (script.js:6:23)

Here is my code

const button = document.getElementById('button');
const input = document.querySelector('input[name="num"]:checked')


button.addEventListener('click', () => {
    console.log(input.value)
    input.value = document.getElementById('output').innerHTML
    let before = document.getElementById('before')
    let after = document.getElementById('after')
    before.style.display = 'none'
    after.style.display = 'flex'
})

I am trying to do a challenge from Frontend Mentor, I need to get access to the input value that is checked, and this error is appearing, but I cannot find a solution

Upvotes: 1

Views: 69

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075785

The null is because querySelector didn't find a matching element, probably because you're looking for a checked input too soon (I'm guessing at page load). Instead, do your DOM query inside the click handler, so you're looking as of the click, not on page load.

const button = document.getElementById("button");

button.addEventListener("click", () => {
    // Look for the checked input now that the button has been clicked
    const input = document.querySelector('input[name="num"]:checked');
    // *** Note the optional chaining (?.) on the below.
    // (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)
    // That way, we get `undefined` instead of an error if no element matched
    // the selector.
    console.log(input?.value);
    /*
    input.value = document.getElementById("output").innerHTML;
    let before = document.getElementById("before");
    let after = document.getElementById("after");
    before.style.display = "none";
    after.style.display = "flex";
    */
});
<input type="button" id="button" value="Click Me">
<label>
    <input type="radio" name="num" value="A"> A
</label>
<label>
    <input type="radio" name="num" value="B"> B
</label>

Upvotes: 1

Related Questions