Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add different confirm message when checking and unchecking a checkbox in plain js

I have two pages where I need to display same behaviour when checking and unchecking a box. On checking, I get the confirm message and upon clicking yes, the box gets checked. For unchecking, I don’t want the display message but just uncheck or another option is to display a confirm message but different from the one when checking the checkbox.

Currently I have this:

let checkbox_elem = document.querySelectorAll('.first_class, .second_class');
checkbox_elem.forEach(elem => {
  elem.addEventListener("click", (e)=> {
    var message = 'Are you sure you want to CHECK this?';
    confirm(message) || e.preventDefault();
  });
});

There are two class ( first_class and second_class) on two different pages, but irrespective of I check or uncheck, it will always display the same message.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just add an if condition for the checked property:

let checkbox_elem = document.querySelectorAll('.first_class, .second_class');
checkbox_elem.forEach(elem => {
  elem.addEventListener("click", (e)=> {
  console.log(e.target.checked);
  if(e.target.checked){
    var message = 'Are you sure you want to CHECK this?';
    confirm(message) || e.preventDefault();
  }
  /*else{
    var message = 'Are you sure you want to UNCHECK this?';
    confirm(message) || e.preventDefault();
  }*/
  });
});
<input type="checkbox" class="first_class" name="scales"
         checked>
  <label for="scales">Scales</label>

Based on the true/false value you can show a different message too. Uncomment the else clause to see that.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading