How to dynamically filter content using checkboxes? - jQuery

对着背影说爱祢 提交于 2019-12-13 04:23:36

问题


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"></script>
<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:


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.



来源:https://stackoverflow.com/questions/3498021/how-to-dynamically-filter-content-using-checkboxes-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!