Hacker inside
Hacker inside

Reputation: 39

Check box not toggling

The toggle check box function is only working once and after the first instance it doesnt work. Any help?

Here is the jsfiddle: http://jsfiddle.net/66gmK/

<script>

$(document).ready(function() {
    $(document).on('click','#1',function(){

          $("INPUT[type='checkbox']").each(function(){
    var Checked = $(this).attr('checked');
    $(this).attr('checked', !Checked);
  }); 


    });

});
</script>

<body>
<form id="form1" name="form1" method="post" action="">
  <p>
    <input name="checkbox" type="checkbox"  id="1" value="0" />
    <label for="1" >Toggle All</label>
  </p>
  <p>
    <input name="checkbox" type="checkbox" id="2" value="0" />
  ahmed</p>
  <p>
    <input name="3" type="checkbox" id="3" value="0" />
    <label for="3">omar</label>
  </p>
</form>
</body>

Upvotes: 1

Views: 1330

Answers (3)

Amit Kumar
Amit Kumar

Reputation: 5962

your jquery on each function , you should not change the property of toggle checkbox.

  $(document).ready(function() {
        $(document).on('click','#1',function(){ 
              $("INPUT[type='checkbox']").not(this).each(function(){             
                var Checked = $(this).prop('checked');          
                $(this).prop('checked', !Checked);
      });       
        });
    });

Demo

Upvotes: 1

cyberoot
cyberoot

Reputation: 340

You can also use

$(document).ready(function() {
     $('#1').on('click',function(){
             var Checked = $(this).prop('checked');
             $.each($("input[type='checkbox']"), function(i,e){
             $(e).prop('checked', Checked);
             });
     });
});

Upvotes: 0

MrCode
MrCode

Reputation: 64526

Move the Checked variable out of the each because the this context changes in the each, it refers to the checkbox in the loop, not the toggle checkbox. Remove the ! not operator when changing the checked property. Also use prop instead of attr for the checked property.

Demo

$(document).ready(function() {
   $(document).on('click','#1',function(){
        var Checked = $(this).prop('checked');  
        $("INPUT[type='checkbox']").each(function(){

            $(this).prop('checked', Checked);
        }); 
    });

});

Upvotes: 4

Related Questions