2
<form>
    <input type="checkbox" name="newsletter" value="Hourly" checked="checked">  <input   type="checkbox" name="newsletter" value="Daily">
    <input type="checkbox" name="newsletter" value="Weekly" checked>
    <input type="checkbox" name="newsletter" value="Monthly">
    <input type="checkbox" name="newsletter" value="Yearly">
    <br><button id="selectall">Select All</button>
</form>
<script>
    var selectall = function() {
        $("input[type=checkbox]").attr("checked", "true");
    };
    $("#selectall").on("click", selectall);
</script>

I have written a JQuery script which will select all the checkboxes when I click on the button "Select All". Now, after selection, I will manually uncheck all the checkboxes and then press "Select All". But this time it fails in selecting all the checkboxes. How to prevent this?

Dhaval Panchal
  • 648
  • 6
  • 26

5 Answers5

3

So that's why we have to use .prop() instead of .attr()

$("input[type=checkbox]").prop("checked","true");    

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

USe prop() instead of attr()

var selectall = function() {
     $("input[type=checkbox]").prop("checked","true");    
};
$("#selectall").on("click", selectall );

Fiddle

Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

try this one

$("#selectall").on("click", function(){
    $("input[type=checkbox]").prop("checked","true");    
});
Ankush Jain
  • 5,654
  • 4
  • 32
  • 57
0

You should use .prop() instead of .attr(). Try this:

var selectall = function() {
     $("input[type=checkbox]").prop("checked","true");    
};
$("#selectall").on("click", selectall );

DEMO

prop() vs attr() ref: .prop() vs .attr()

Community
  • 1
  • 1
Kiran
  • 20,167
  • 11
  • 67
  • 99
0

Please make sure your code should be in dom ready function inside. and use .prop() to check all the checkboxes

$(function() {

       var selectall = function() {
       $("input[type=checkbox]").prop("checked",true);    
       };
       $("#selectall").on("click", selectall );
});
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49