Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hide div when checkbox checked, show on unchecked

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.

like image 953
user2035638 Avatar asked Feb 07 '13 17:02

user2035638


People also ask

How do I show and hide input fields based on checkbox?

To show or hide the field, we are applying CSS through jQuery css() method. We are passing CSS display property. To hide the field, we set the display property to none and to show it we set the display property block. So you have seen how to show or hide input field depending upon a checkbox field.

What does hide () do in jQuery?

jQuery hide() Method The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.


2 Answers

Make sure to use the ready event.

Code:

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

    });
});
like image 189
gdoron is supporting Monica Avatar answered Oct 21 '22 11:10

gdoron is supporting Monica


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
});
like image 44
overflow Avatar answered Oct 21 '22 11:10

overflow