How to uncheck all radio buttons and checkboxes using jQuery

Learn how to use jQuery to reset all radio buttons and checkboxes AT ONCE in a page

- UPDATE -

My friend Wellington sent me this code right after I've published this post:

$('input:checked').removeAttr('checked');

This should get all the checked items and remove the "checked" attribute.

- Original post -

Recently I have come across a very interesting problem in a project I am working on. I had to uncheck all checkboxes at once. It was fine by using a simple .each on jQuery. After that the requirements changed and I had to add radio buttons and they weren't working with the code I already had. That was fixed with one more line. Let's see how it was done.

Suppose I have 3 checkboxes and I want to clear all of them at once. Normally I would do something like this:

$('#clear-all').click(function () {
	$(':checkbox').each(function () {
		$(this).removeAttr('checked');
	})
});

Very simple, very generic and it works like a charm. However, suppose that I have to add some radio buttons. The code above will not work with radio buttons, as mentioned before. If you want to uncheck all the radio buttons and checkboxes you will need to add one single line (in bold):

$('#clear-all').click(function () {
	$(':checkbox').each(function () {
		$(this).removeAttr('checked');
		$('input[type="radio"]').prop('checked'false);
	})
});

According to jQuery website the .prop is gets the value of a property for the first element in the set of matched elements or set one or more properties for every matched element. In another words it will look for the "checked" property and, if you want, it can change its value as well.

Easy, simple and clean.