How to process multiple checkboxes with jQuery
The functionality isn’t new: you have a list of stuff and want checkboxes before the elements so you can mass-process them. In my case, I wanted to set a number of list elements to a certain state (which in this case means a status flag in the database) so the need arose to fetch all selected elements (where the checkbox is checked), stuff them into an AJAX function and deselect the items afterwards.
For this example, my list looks like:
<input type="checkbox" value="1" name="check[]" /> 1<br />
<input type="checkbox" value="2" name="check[]" /> 2<br />
<input type="checkbox" value="3" name="check[]" /> 3<br />
<input type="checkbox" value="4" name="check[]" /> 4<br />
<button>send</button>
Now I want to get alle checked checkboxes with jQuery and process them with AJAX. For this task, I employ jQuery’s each() functionality:
$('button').click(function(){
$(':checkbox:checked').each(function(){
$.post('process.php', { checkbox: $(this).attr('value') });
});
});
Now what does that do?
$(':checkbox:checked').each(function(){
tells jQuery to get all checked checkboxes and via each() do something (function()…)
$.post('process.php', { checkbox: $(this).attr('value') });
For each value that we get, we want to send an AJAX call to process.php and pass the current value as parameter “checkbox”, which we can pick up with PHP. If you like, you can also add a callback function to the AJAX call (e.g. an alert which says “Thanks I’ve used your data” or something alike).
