Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!