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.
>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.