It is recommended to use prop instead of attr if the checkbox (multiple selection) or radio (radio) is added checked attribute
Single selection attr Click once to add Checked= "Checked" property, click on the second page to show the selected state
Multiple selection attr only the first click is valid, the rest is not identified as selected
1. Single-selection Example
HTML code <ul> <liclass="Li_check"> <inputclass="Check_box" checked="checked"Type="Radio"Name="Sort"Value="1"Id="Sort_one"/><label for="Sort_one">1</label> </li> <liclass="Li_check"> <inputclass="Check_box"Type="Radio"Name="Sort"Value="2"Id="Sort_two"/><label for="Sort_two">2</label></li> <liclass="Li_check"> <inputclass="Check_box"Type="Radio"Name="Sort"Value="3"Id="Sort_three"/><label for="Sort_three">3</label></li> </ul>
//JS Code$(". Check_box"). Click (function () {if($( This). Prop ("checked") !="checked") { $(". Check_box"). each (function () {$ ( This). Removeattr ("checked"); }); $( This). Prop ("checked","checked"); } });
2. Multiple selection examples
HTML code
<span class= "Check-all" > Full selection </span>
<ul> <liclass="Li_check"> <inputclass="Check_box" checked="checked"Type="checkbox"Name="Sort"Value="1"Id="Sort_one"/><label for="Sort_one">1</label> </li> <liclass="Li_check"> <inputclass="Check_box"Type="checkbox"Name="Sort"Value="2"Id="Sort_two"/><label for="Sort_two">2</label></li> <liclass="Li_check"> <inputclass="Check_box"Type="checkbox"Name="Sort"Value="3"Id="Sort_three"/><label for="Sort_three">3</label></li> </ul>
//JS Code$(". Check_box"). Click (function () {if($( This). attr ("checked") =="checked") { $( This). Removeattr ("checked","checked"); } Else { $( This). attr ("checked","checked"); } }); $ (function () {varClick =0; $(". Check-all"). Click (function () {Click= Click +1; if(Click%2==1) { $(". Check_box"). Prop ("checked","checked"); $(". Check_box"). each (function () {$ ( This). attr ("checked","checked"); }); } Else { $(". Check_box"). Removeattr ("checked","checked"); $(". Check_box"). each (function () {$ ( This). Removeattr ("checked","checked"); }); } }); });
Single selection and clear selection in jquery