As soon as I remove the attribute, I cannot add it

I'm trying to check the "Select All" box, but when I uncheck it and select it again, it will no longer select the fields. Although it works for the first time.

This is my code:

HTML:

<div id="Everything"> <input type="checkbox" id="all" />Select All <br /> <br /> <div id="selectThese"> <input type="checkbox" id="First" />First <br /> <input type="checkbox" id="Second" />Second <br /> </div> </div> 

JS:

 $(function () { $("#Everything").on("click", "#all", function () { var carStatus = $("#all").is(':checked'); if (carStatus == true) { $("#selectThese input").attr("checked", "checked"); } else { $("#selectThese input").removeAttr("checked"); } }); }); 

Jsfiddle Link: http://jsfiddle.net/Epsju/1/

+4
source share
3 answers

For this you need to use prop() , and since it takes a boolean value to check and uncheck an element, you can use your variable directly or simply flip the variable and use this.checked :

 $(function () { $("#Everything").on("change", "#all", function () { $("#selectThese input").prop("checked", this.checked); }); }); 

Fiddle

+5
source

http://jsfiddle.net/Epsju/6/

Use change , and your fiddle uses #car when it should use #all .

 $(function () { $("#Everything").on("change", "#all", function () { $('#selectThese :checkbox').prop('checked', $(this).is(':checked')); }); }); 
+1
source

Try the following: Demo

 $(function () { $("#Everything").on("change", "#all", function () { $('#selectThese :checkbox').prop('checked', $(this).is(':checked')); }); }); 

And vice versa>

 $('#selectThese :checkbox').on('change', function () { $('#all').prop('checked', $('#selectThese :checkbox:checked').length == $('#selectThese :checkbox').length) }); 
+1
source

Source: https://habr.com/ru/post/1479198/


All Articles