Home > Mobile >  Need help to isolate snippet into function in JavaScript
Need help to isolate snippet into function in JavaScript

Time:10-05

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?

CodePudding user response:

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();
}

CodePudding user response:

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

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

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

  • Related