mardi 21 février 2017

html, javascript, how to know when checkbox change state

I'm facing a problem. I have something like this.

Html:

<ul>
   <li><span><input name="xt" id="xt" type="checkbox" /> Check All</span></li>
   <li><span><input name="x1" id="x1" type="checkbox" class="mark" /> X1</span></li>
   <li><span><input name="x2" id="x2" type="checkbox" class="mark"/> X2</span></li>
   <li><span><input name="x3" id="x3" type="checkbox" class="mark"/> X3</span></li>
   <li><span><input name="x4" id="x4" type="checkbox" class="mark"/> X4</span></li>
</ul>
<div id="divX2" hidden="hidden">
   <h4>Mostrando X2</h4>
</div>

Javascript:

<script>
        $(function (){
            $("#xt").click(function (){
                var check = $(this).prop("checked");
                $(".mark").prop("checked", check);
            });

            $("#x2").change(function (){
                console.log("change x2");
                if($(this).prop("checked")){
                    $("#divX2").show();
                }
                else{
                    $("#divX2").hide();
                }
            });
        })
    </script>

My goal is to show divX2when x2 is checked either by clicking x2 or clicking xt. This works fine when x2 is clicked but doesn't work when xt is clicked. Note the line console.log("change x2"); in the change event handler of x2. When I clic xt, x2 looks checked but the change event is never fired. Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire