Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hide text when checkbox is unchecked using jquery

the checkboxes are checked by default. if unchecked they should hide the text. how do i hide or show the text in jquery?

html:

    <div class="check">
<p><input type="checkbox" value="Name" id="name" checked /> <label for="name">Name</label></p>  
<p><input type="checkbox" value="Reference " id="reference" checked /> <label for="reference">Reference</label></p>
    </div>

    <div id="nametxt"> Show Name TEXT </div>
    <div id="reftxt"> Show Ref TEXT </div>
like image 916
input Avatar asked May 01 '26 15:05

input


2 Answers

Change the id of <div id="reftxt"> to <div id="referencetxt"> and then you can do this:

$('div.check input:checkbox').bind('change',function(){
    $('#'+this.id+'txt').toggle($(this).is(':checked'));
});

The change event will fire if its clicked on or if someone uses the keyboard to check/uncheck the checkbox.

As long as the ID's of the text divs are always checkbox ID + 'txt' and are in div.check then this will handle those too. Keeps you from having to repeat yourself as you get more checkboxes.

like image 58
PetersenDidIt Avatar answered May 04 '26 04:05

PetersenDidIt


<script type="text/javascript" charset="utf-8">
    $(document).ready(function() {
        $("#name").click(function() {
            if($('#name:checked').length) {
                $("#nametxt").show();
            } else {
                $("#nametxt").hide();
            }
        });

        $("#reference").click(function() {
            if($('#reference:checked').length) {
                $("#reftxt").show();
            } else {
                $("#reftxt").hide();
            }
        });
    })
</script>
like image 30
Makram Saleh Avatar answered May 04 '26 05:05

Makram Saleh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!