tommarshallandrews
tommarshallandrews

Reputation: 3

Jquery: setting div hide / show with checkbox checking initial state

I am trying to hide divs when the associated checkbox is checked.

To get it to work with the initial jstate of the checkbox I added triggerHandler('click').

This works fine for the first checkbox but not for any others.

Any suggestions?

Fiddle here: http://jsfiddle.net/tb5Yt/100/

Many thanks.

HTML

1<input type = "checkbox" id = "1" checked>
2<input type = "checkbox" id = "2" >
3<input type = "checkbox" id = "3" checked>

<div class = "1">
  //Contains 1 elements remove when checked
</div>

<div class = "2">
  //Contains 2 elements remove when checked
</div>

<div class = "3">
  //Contains 3 elements remove when checked
</div>

Jquery

$(document).ready(function() {

$("input[type=checkbox]").click(function()

{
    divId = $(this).attr("id");

    if ($(this).is(":checked")) {
        $("." + divId).hide();
    }
    else if ($(this).not(":checked")) {
        $("." + divId).show();
    }

}).triggerHandler('click');

});

Upvotes: 0

Views: 5613

Answers (3)

iMoses
iMoses

Reputation: 4348

Took the liberty to modify your code.

$(document).ready(function() {
    function toggleDiv() {
        var $this = $(this);
        $("." + $this.attr('id'))[$this.is(':checked') ? 'hide' : 'show']();
    }
    $('input:checkbox').each(toggleDiv).click(toggleDiv);
});​

http://jsfiddle.net/tb5Yt/123/

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337600

You need to execute your code on load of the page, as well as when the click event occurs, try this:

$("input[type=checkbox]")
    .each(setDivs) // on load
    .change(setDivs); // on click

function setDivs() {
    divId = $(this).attr("id");

    if ($(this).is(":checked")) {
        $("." + divId).hide();
    }
    else {
        $("." + divId).show();
    }
}

You'll also notice how I amended the else if clause to simply an else, and also changed the click event to change to allow users to select options using their keyboard too.

Example fiddle

Upvotes: 0

musefan
musefan

Reputation: 48425

First of all you shouldn't do the else if part. else alone will do.

second I would try calling the click function on the same selector. please try the following code:

$(document).ready(function() {

    $("input[type=checkbox]").change(function()
    {
        var divId = $(this).attr("id");

        if ($(this).is(":checked")) {
            $("." + divId).hide();
        }
        else{
            $("." + divId).show();
        }

    });
    $("input[type=checkbox]").change();

});​

EDIT: Try using the change event instead. See this example.

Upvotes: 1

Related Questions