Solving a Large Number of Checkboxes with Javascript

Posted on Posted in Javascript, PHP

So this is an interesting problem that I think others may have run into that I wanted to share my solution to.

We have an internal application that has a large pre-compilation report based upon thousands of chemicals within thousands of products. It takes a trained eye to literally go through all of those products individually for each client possible. It sounds exhausting to me. Basically every chemical combo has a checkbox that requires further evaluation.

Well, one client had so many chemicals on site that I ran into the POST buffer for max inputs. Now, there are ways around this. One approach is to create or modify your htaccess file to increase the size of the input variables allowed.

php_value max_input_vars 10000

Now to me this solution is a little (or a lot) obscene because you open yourself up to attacks especially DDoS because when you open the flood gates, it’s what happens. Not to mention, you may need to rethink the idea of a bunch of checkboxes anyway!

I tried that second approach with my internal customers and I got nowhere with them even explaining the limitations. So what else could be done?

Javascript to the rescue!

I left all the checkboxes and miscellaneous stuff and instead use a combination of creating my own form via the actual checked boxes and putting the values into a JSON array into one variable that I was then able to parse with PHP on the backend. I was lucky to some extent because let’s be real, if you are using checkboxes for anything other than storing tinyint values for ids, you got design problems.

So what does it look like?

var myIds = [];

$('input.my_id:checked').each(function(index, value){
    var my_id = $(this).attr('data-id');

    if(msdsId.indexOf(my_id) == -1){

Using the jQuery each function we can loop through the checked boxes that I am looking for. We use data attributes to store the associated id. (Quick side note: I love data-* attributes). Also one other note about this code is that it then checks the array to make sure we have no duplicates.

		var ids = JSON.stringify(myIds);

		//Create a data structure to pass to the AJAX call.
		var data = {
			client_num: client_num,
			year: year,
			ids: ids,

And then from there, you can JSON.stringify the array which can then be parsed on the backend. The data object is passed as part of an AJAX call later.

It was an interesting problem I ran across where I didn’t readily find anything on the internet to solve. Handling a large number of inputs, particularly checkboxes. I hope this solution helps someone else out there.