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

111
Visualizações
How to add confirm addeventlistener to different view pages in rails

I have two different views: edit.html.erb and create.html.erb I want to add similar functionality onclick a checkbox on both the pages but want to avoid writing redundant code in both the files:

Currently what I am doing in both the files: In create.html.erb

<script>
    function onclick (event) {
        var message = 'Are you sure ?';
        confirm(message) || event.preventDefault();
        }
    var elem = document.getElementById('create');
    elem.addEventListener('click', onclick);
</script>

In edit.html.erb

<script>
    function onclick (event) {
        var message = 'Are you sure ?';
        confirm(message) || event.preventDefault();
        }
    var elem = document.getElementById('edit');
    elem.addEventListener('click', onclick);
</script>

Ideally I want to have a js file where both these events can be captured when clicking on either create or edit instead of writing this method individually on both files. What is a good way to do DRY here.

about 4 years ago · Santiago Gelvez
1 Respostas
Responde à pergunta

0

I would just do it the same way that Rails UJS does - by adding an event listener that targets elements with a data-confirm attribute:

function handleConfirm(e){
  if (!event.target.matches('[data-confirm]')){ return; };
  const attr = e.target.dataset.confirm;
  const message = attr.length > 0 ? attr : 'Are you sure ?';
  window.confirm(message) || e.preventDefault();
}

document.addEventListener('click', handleConfirm);
<button>No confirmation</button>
<button data-confirm>Standard message</button>
<button data-confirm="REALLY???!!">A button with a custom text</button>

about 4 years ago · Santiago Gelvez 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