Reputation: 61
I am trying to verify if my checkbox is checked. I have looked up many solutions, and they all point to this :
html :
<body>
<input type="checkbox" id="terms" name="terms" />
<label for="terms">Agree with terms</label>
javascript :
let checkbox = document.querySelector("#terms");
console.log(checkbox.checked);
But the console is returning :
"Uncaught TypeError: Cannot read properties of null (reading 'checked')"
There is no other code interfering with this as I stripped it down to this small example to see if my project was interfering with the functionality, but even with the most basic code '.checked' is returning an error. Has there been an update to this feature?
Upvotes: 1
Views: 53
Reputation: 4415
You will run into unexpected issues if you use defer
.
Instead, use the DOMContentLoaded
event to trigger your script.
Using defer
allows that script to be executed after the DOM is done being parsed, but before the DOM content is loaded.
It’s likely that you’re deferred script will run too soon and crash when you try to access an element that doesn’t exist yet.
You can link your script in the <head>
as long as you have it run when that event fires off.
document.addEventListener('DOMContentLoaded', function () {
let checkbox = document.querySelector("#terms");
checkbox.addEventListener('change', () => {
console.log(checkbox.checked);
})
})
EDIT: To answer the question from your comment above, linking to the JavaScript file in the head
means that it will run before the html
is built.
Putting the code in a script tag in the html means that it won’t be executed until DOMContentLoaded
has triggered.
That happens after the link using defer
and after the script is executed from the head
.
Wrap your code up to only execute on DOMContentLoaded
and you’ll avoid a lot of headaches in the future 😎
Upvotes: 0
Reputation: 61
I figured out the issue, I was not including 'defer' in my script.js link. Its all fixed thank you!
Upvotes: 0
Reputation:
<input type="checkbox" id="terms" name="terms" />
<label for="terms">Agree with terms</label>
<script>
let checkbox = document.querySelector("#terms");
checkbox.addEventListener('change', () => {
console.log(checkbox.checked);
})
</script>
or
let checkbox = document.querySelector("#terms");
console.log(checkbox.checked);
Upvotes: 1