21

I am trying to hide div when user clicks on checkbox, and show it when user unchecks that checkbox. HTML:

<div id="autoUpdate" class="autoUpdate">
   content
</div>

jQuery:

<script>
$('#checkbox1').change(function(){
        if (this.checked) {
            $('#autoUpdate').fadeIn('slow');
        }
        else {
            $('#autoUpdate').fadeOut('slow');
        }                   
    });
</script>

I am having a hard time to get this working.

1

2 Answers 2

54

Make sure to use the ready event.

Code:

$(document).ready(function(){
    $('#checkbox1').change(function(){
        if(this.checked)
            $('#autoUpdate').fadeIn('slow');
        else
            $('#autoUpdate').fadeOut('slow');

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

4 Comments

I believe this has to be the issue, as the code works fine on jsFiddle: jsfiddle.net/mxRCz
I found where I had my problem. <label> tags was causing this issue. <label id="checkbox1"><input type="checkbox" id="checkbox1" checked="checked" /></label> Working if I remove <label> tags. Thank you!
The right way to do it wth label would be: <label for="cbText">Blabla</label> <input type="checkbox" value="" id="cbText" /> so the checkbox has to be outside of the label tag
note: make sure you are hitting the checkbox input id/class
2

HTML

<input type="checkbox" id="cbxShowHide"/><label for="cbxShowHide">Show/Hide</label>
<div id="block">Some text here</div>

css

#block{display:none;background:#eef;padding:10px;text-align:center;}

javascript / jquery

$('#cbxShowHide').click(function(){
this.checked?$('#block').show(1000):$('#block').hide(1000); //time for show
});

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.