0

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?

3
  • 2
    You need to pass the object in your toggle() as in toggle(this) and then function toggle(obj) { $(obj).is(":checked") ? show() : hide(); } Commented Oct 4, 2021 at 8:38
  • Thank you @CarstenLøvboAndersen it worked! Please consider posting this as an answer. Commented Oct 4, 2021 at 8:41
  • See call No need to pass this in as a parameter (not that that's a bad way to do it), change toggle() to toggle.call(this) then this inside toggle will be the same this inside .change (ie no code change to your toggle function) Commented Oct 4, 2021 at 9:19

2 Answers 2

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

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

3 Comments

Fine until you want a second toggle, then you have to have 2 separate toggle functions instead of reusing one with a parameter.
@freedomn-m yes, it happens when he reuse it for another checkbox. But how about in case he wants to reuse it in another function only?
Indeed OPs "so I may reuse it" is entirely unclear. Reuse the method to toggle #some-id or reuse the method to toggle #another-id. (not my downvote, it's fine, just not what what people would define as "reusable")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.