Search code examples
javascriptjquerytoggle

Jquery If Statement - Toggle Functions


                    $(document).ready(function() {

            $("span#label_Flat").hide();
            $("span#added_Flat").hide();
            $("span#removed_Flat").hide();



            if ($('#Flat:checked').val() != false) {

                $('#Flat').click(function() {
                    $("span#label_Flat").toggle();
                    $("span#removed_Flat").toggle();

                });

            } else {

                $('#Flat').click(function() {
                    $("span#label_Flat").toggle();
                    $("span#added_Flat").toggle();

            });                 
        });

Can anyone point me in the direction of why this isnt working?

I want to hide three span and only toggle two of them to be visible depending on if the checkbox is checked or not.

Currently, the span are not hidden, and therefore do not toggle between hide and show as they should.

The html is:

<input id="Flat" type="checkbox" name="Flat" checked />


<p>
<span id="label_Flat">Flat: </span>
<span id="added_Flat">Added</span>
<span id="removed_Flat">Removed</span>
</p>

Thanks in advance for help.

Example can be seen here: http://jsfiddle.net/WEq5u/10/


Solution

  • I think you are looking for this. To find whether the checkbox is checked, you can just use this.checked property which will return true if it is checked or else false.

            $(document).ready(function() {
    
                $("span#label_Flat").hide();
                $("span#mp_Flat").hide();
                $("span#removed_Flat").hide();
    
                $('#Flat').click(function() {
                    if(this.checked){
                       $("span#label_Flat").toggle();
                       $("span#removed_Flat").toggle();
                    }
                    else{
                       $("span#label_Flat").toggle();
                       $("span#mp_Flat").toggle();
                    }
                }).click();
    
            });