skip to Main Content

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


  1. The difference is very simple. lets understand by a simple example.

    var checkbox = document.getElementById('vehicle1').checked;
    checkbox = true;
    

    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.

    var checkbox1 = document.getElementById('vehicle1');
    checkbox1.checked = true;
    

    The proper reference example will be something like this

    var checkbox1 = document.getElementById('vehicle1');
    var dummyCheckbox = checkbox1
    dummyCheckbox.checked = true;
    

    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.

    Login or Signup to reply.
  2. reference and value type

    var checkbox = document.getElementById(ID).checked;
    checkbox = true;
    

    that checkbox is bool, it is just a value

    var checkbox = document.getElementById(ID);
    checkbox.checked = true;
    

    that checkbox is object, it is input element itself
    you can modify it’s property

    try

    typeof checkbox 
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search