A couple of weeks ago, a client of ours needed a simple way to select some or all options in a multiple select form element that contained hundreds of options. Basically, they had various State/County combination's that they needed to assign to different pieces of content.
So Article X might need to select all Counties in State Y. In other cases, an article might simply need to be tagged will all available options in a particular select element. The point is, holding the Command key and clicking through hundreds of select options was becoming a bit tedious. They asked if there was a an easier way. jQuery to the rescue! So here are the tasks that I needed jQuery to help with:
- Select all elements with a single click
- Deselect all elements with a single click
- Select elements that match some value. (contain “red”) with a single click
After spending some time digging through the documentation on jQuery.com - I realized all I needed to accomplish these tasks was to attach/alter the selected attribute of any or all option elements. I could attach click functions to radio inputs that would carry out each individual task. To select all elements I could use the “.each” function to loop through the option elements and attach the “selected=’selected’” along the way. For selecting only some elements, (contains "red") I could use the “:contains” selector.
Here is what I came up with:
$("input#all").click(function(){
$("#colors").each(function(){
$("#colors option").attr("selected","selected");
});
});
$("input#red").click(function(){
// code for selecting all elements with id=colors that contain the value red, rinse and repeat as needed
$("#colors option:contains('Red')").attr("selected","selected");
// additionally disable the element so the user can't muck with it
$("#colors").attr("disabled","disabled");
});
It worked wonderfully! There was just one problem: with each click that was supposed to only select certain elements it was simply adding to what was already selected. So you might end up with Red and Green elements selected - this was not the desired result. I realized that when selecting elements that matched some value, I would first need to deselect anything that may already be selected in that particular element. This was easily accomplished like so:
$("input#red").click(function(){
// loop through each option in the selected element, remove the selected attribute
$("#colors").each(function(){
$("#colors option").removeAttr("selected");
});
// code for selecting all elements with id=colors that contain the value red, rinse and repeat as needed
$("#colors option:contains('Red')").attr("selected","selected");
// additionally disable the element so the user can't muck with it
$("#colors").attr("disabled","disabled");
});
After adding another function for deselecting all options, the work was done and better yet, our client was ecstatic. We hope other developers out there find this tip useful. Demo and source code found below: