Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda