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

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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