Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda