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

124
Visualizações
Need help to isolate snippet into function in JavaScript

I have a checkbox that when checked shows some content on my page. If I uncheck it, the content is hidden.

I am trying to isolate the internal behaviour of that function into another function so I may reuse it:

    $('#some-id').change(function(){
        if ($(this).is(":checked")){
            show();
        } else {
            hide();
        }
    });

This is what I have tried:

    $('#some-id').change(function(){
        toggle();
    });

    function toggle() {
        $(this).is(":checked") ? show() : hide();
    }

But now it worked only for hiding the content when unchecking the field, but it does not show the content when the field is checked again anymore.

Is there any syntax error with that?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Just pass a the checkbox object to the toggle function, otherwise the code wont know what to toggle.

let $checkBox = $('#somecheckbox'); //get the checkbox
$checkBox.change(function (){
  toggle($checkBox) //pass the checkbox to function
});

function toggle($checkBox) {
  $checkBox.is(":checked") ? show() : hide();
}

you could do that also with vanilla js and without jQuery pretty easily:

let checkbox = document.getElementById('someId');
checkbox.addEventlistener('change', () => {toggle(checkbox)});


function toggle(checkbox) {
   checkbox.checked ? hide() : show();
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Change $(this) to $('#some-id') in function toggle()

$('#some-id').change(function() {
  toggle();
});

function toggle() {
  $('#some-id').is(":checked") ? show() : hide();
}

about 4 years ago · Juan Pablo Isaza 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