Submit your widget

jQuery Selecting Multiple Select Form Elements on the Fly

Created 14 years ago   Views 7358   downloads 1830    Author Chris
jQuery Selecting Multiple Select Form Elements on the Fly
View DemoDownload
118
Share |
  1. Select all elements with a single click
  2. Deselect all elements with a single click
  3. 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.