0

I am trying to hide/show elements based on a checkbox change event. The event does get triggered, but the hide/show isn't working.

This is my code:

$("#inlineCheckbox3").change(function() {   
    $checked = $(this).is(":checked");
    console.log($checked); //logs true or false properly
    if (!$checked) {
        $("#myDiv").hide(); //this doesnt work at all.
        alert('test'); //alert is working
    }
});

If I put something like:

if ($("#inlineCheckbox3").is(":checked")) {
    $("#myDiv").hide();
}

it does work on my console.


Solution:

There was a second .click() handler in my JavaScript that caused the div to be hidden reappear right away. This way it seemed like it didnt get hidden.

6
  • Share the HTML code and Script in JSFiddle Or there is a functionality here on stackoverflow. It is always helpful and easier to figure out what is wrong. Commented Feb 8, 2017 at 13:05
  • 3
    So if the alert is working, this has nothing to do with the checkbox changed event. By "doesn't work at all" do you mean #myDiv doesn't get hidden? Commented Feb 8, 2017 at 13:05
  • please also provide the needed html markup, best in form of a jsfiddle or the functionality here on stackoverflow Commented Feb 8, 2017 at 13:05
  • 4
    @Kumar_Vikas: Ideally not a fiddle, but rather a runnable minimal reproducible example using Stack Snippets (the [<>] toolbar button) right here on site. Commented Feb 8, 2017 at 13:06
  • 1
    Definitely will need the HMTL, as that's likely the issue. Commented Feb 8, 2017 at 13:07

1 Answer 1

4

Try this (Run CODE Snippet & check / uncheck the checkbox):

(function($){
  $("#inlineCheckbox3").change(function() {   
    $checked = $(this).is(":checked");
    if (!$checked) {
        $("#myDiv").hide();
    }
    else {
      $("#myDiv").show();
    }
  });
})(jQuery);
#myDiv {
  width: 200px;
  height: 50px;
  background-color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="inlineCheckbox3" type="checkbox" checked="checked">
<div id="myDiv"></div>

What I did differently:

  1. In your CODE you only added hide() function, didn't show() it back again when checkbox was checked.

  2. Depending on the scope, you'll not always be able to access $. That's why I wrapped my CODE with (function($){})(jQuery);

Most likely you were getting error in one of these two.

Sign up to request clarification or add additional context in comments.

Comments

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.