skip to Main Content

I want check the checkbox, without trigger the alert.

<div onclick="alert('test')">
Lorem ipsum dolor sit amet consectetur, adipisicing elit.
    <input type="checkbox">
</div>

I have tried pointer-events: none and z-index: 1000

2

Answers


  1. Try this;

    const checkbox = document.getElementById('myCheckbox')
    const div= document.getElementById('myDiv')
    var checkboxPrevState=checkbox.checked;
    
    div.addEventListener('click',(event)=>{
      var checkboxCurrentState=checkbox.checked;
      if(checkboxPrevState==checkboxCurrentState){
          alert("test");
      }
      else{
        checkboxPrevState=checkboxCurrentState;
      }
    })
    <div id="myDiv">
    Lorem ipsum dolor sit amet consectetur, adipisicing elit.
        <input id="myCheckbox" type="checkbox">
    </div>
    Login or Signup to reply.
  2. It is generally not a good idea to use inline event handlers.

    Use event delegation instead. Something like:

    document.addEventListener(`click`, handle);
    
    function handle(evt) {
      if (+evt.target.dataset.clickable === 1) {
        evt.target.dataset.nclicks = +evt.target.dataset.nclicks + 1;
        console.clear();
        console.log(`You clicked ${evt.target.dataset.nclicks} times!`);
      }
    }
    <div data-clickable="1" data-nclicks="0">
      Lorem ipsum dolor sit amet consectetur, adipisicing elit.
      <div><input type="checkbox"> check me</div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search