jQuery Selecting Multiple Select Form Elements on the Fly
- 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.
You might also like
Tags
accordion accordion menu animation navigation animation navigation menu carousel checkbox inputs css3 css3 menu css3 navigation date picker dialog drag drop drop down menu drop down navigation menu elastic navigation form form validation gallery glide navigation horizontal navigation menu hover effect image gallery image hover image lightbox image scroller image slideshow multi-level navigation menus rating select dependent select list slide image slider menu stylish form table tabs text effect text scroller tooltips tree menu vertical navigation menu