skip to Main Content

My HTML :

<div id="PDF">
    <input type="checkbox" id="pdf" name="pdf" value="pdf">
    <label for="pdf">PDF</label>
</div>

My JS :

document.addEventListener('change',function(event){
    if(event.target.id == "pdf"){
        if(event.target.checked == true){
            event.target.label.style.fontWeight = "bold";
        }
        else{
            event.target.label.style.fontWeight = "normal";
        }
    }
});

To my utter dismay, when I execute the code, I am greeted with this error:

Uncaught TypeError: Cannot read properties of undefined (reading
‘style’)

How do I fix this issue?

3

Answers


  1. There are two main issues here. Firstly, the event target has no attribute of label. You should just select the label explicitly and change the styles. Secondly, I would recommend adding the event listener to only the #pdf div rather than the whole document. This way, you won’t need to check for the ID and the event listener won’t be fired on every change. For example:

    document.getElementById("pdf").addEventListener("click", event => {
      const label = document.querySelector("label[for=pdf]");
      if(event.target.checked == true){
        label.style.fontWeight = "bold";
      }
      else{
        label.style.fontWeight = "normal";
      }
    })
    
    Login or Signup to reply.
  2. I hope this finds you well..

    let divid = document.getElementById('PDF');
    let checkid = document.getElementById('pdf');
    let labelid = document.getElementById('label');
    
     checkid.addEventListener( "change", () => {
           if(checkid.checked){
    label.style.fontWeight='bold';
    }
    else{
    label.style.fontWeight='normal';
    }
          });
    <div id="PDF">
        <input type="checkbox" id="pdf" name="pdf" value="pdf">
        <label for="pdf" id="label"> PDF</label>
    </div>
    Login or Signup to reply.
  3. Try this code actually target can have multiple labels.
    So property is not label it is labels.

    <div id="PDF">
            <input type="checkbox" id="pdf" name="pdf" value="pdf">
            <label for="pdf">PDF</label>
        </div>
        <script>
            document.addEventListener('change', function (event) {
                if (event.target.id == "pdf") {
                    if (event.target.checked == true) {
                        event.target.labels[0].style.fontWeight = "bold";
                    }
                    else {
                        event.target.labels[0].style.fontWeight = "normal";
                    }
                }
            });
    
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search