Trying to create a selector/variables in javascript but I can’t get it to work.
This one doesn’t work.
var checkbox = document.getElementById(ID).checked;
checkbox = true;
This one works
var checkbox = document.getElementById(ID);
checkbox.checked = true;
What is the difference?
Which part of the javascript rules have I managed to avoid by accident ?
2
Answers
The difference is very simple. lets understand by a simple example.
Above you simply extracted the value of checkbox and later making change in the variable directly which has no relation directly with the DOM element by id vehicle1
and In the below example you simply tried to change the checked value of checkbox directly.
The proper reference example will be something like this
you can go through this article to get the idea https://www.freecodecamp.org/news/javascript-assigning-values-vs-assigning-references/#:~:text=When%20we%20assign%20a%20reference,variable%20affect%20the%20original%20value.&text=In%20the%20example%20above%2C%20the%20variable%20array2%20is%20assigned%20a,to%20the%20original%20array%20array1%20.
reference and value type
that checkbox is bool, it is just a value
that checkbox is object, it is input element itself
you can modify it’s property
try