views:

18

answers:

1

Hey all,

I am trying to dynamically filter out content using checkboxes and jquery.

Being new to jquery, I'm not sure on how to do this properly, so if any can help that would be great.

I have got this code:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript" >
        $(document).ready(function(){
            $("#test").change(function()
            {    
                if ($(this).is(":checked"))
                {
                        $("#example").hide();

                }else{
                        $("#example").show();
                }

            });
        });
    </script>
</head>
<body>
    <input type="checkbox" id="test"/>
    <input type="checkbox" id="test2"/>

    <div id="example">Example</div>
    <div id="example2">Example2</div>
</body>
</html>

I am trying to make it so that both checkboxes work dynamically, meaning that I don't have to hard code the id in like above, which only works for the first checkbox. I want to have multiple checkboxes so was wondering how to do this. Do I get the id on check and insert somehow?

Any help would be great, thanks.

+1  A: 

I could give your checkboxes a class like this:

<input type="checkbox" id="test" class="cb" />
<input type="checkbox" id="test2" class="cb"/>

<div id="example">Example</div>
<div id="example2">Example2</div>​​​​​​​​​​​​​​​​

The use that when binding and get the ID on the fly, like this:

$(document).ready(function(){
  $(".cb").change(function() {    
    $("#" + this.id.replace('test', 'example')).toggle(this.checked);
  }).change();  //match the initial show/hide match
});​

You can give it a try here, instead of show/hide this uses .toggle(bool), and we're selecting the matching <div> element by transforming the ID, replacing test with example and fetching that element.

Nick Craver