I have several forms that require the use of a few multi-select boxes. (list of affiliates, list of sources, list of products, etc…) Each form could have it’s own set of multi-boxes, for whatever my clients need.
I also created a link that allows the user to “select all” the options in any of the multi-select boxes. And so far things work great! But I want to make the jquery a little more smart.
Here’s an example of what I’ve coded:
<table>
<tr>
<td><div id="allaffs" class="selectAll">select all</div></td>
</tr>
<tr>
<td>
<select name="affid[]" id="affid" size="15" style="width:230px;height:300" multiple="multiple">
<option value="0" selected="selected">--no affiliate assigned--</option>
<? while($r = mysql_fetch_array($somequerystuff)){ ?>
<option value="<?php echo $r['affid']; ?>" selected="selected"><?php echo $r['affname']; ?></option>
<? } ?>
</select>
</td>
</tr>
</table>
<table>
<tr>
<td><div id="allsources" class="selectAll">select all</div></td>
</tr>
<tr>
<td>
<select name="sourceid[]" id="sourceid" size="15" style="width:230px;height:300" multiple="multiple">
<option value="0" selected="selected">--no source assigned--</option>
<? while($r = mysql_fetch_array($somequerystuff)){ ?>
<option value="<?php echo $r['sourceid']; ?>" selected="selected"><?php echo $r['sourcename']; ?></option>
<? } ?>
</select>
</td>
</tr>
</table>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".selectAll").click(function(){
var theID = $(this).attr('id');
if(theID=='allaffs'){ $("#affid option").attr("selected","selected"); }
if(theID=='allsources'){ $("#sourceid option").attr("selected","selected"); }
});
});
</script>
And this totally works. But I tend to add more multi-boxes for other filtering reasons.
I want to make the jquery detect the click event for the .selectAll class, but make it smart enough to select all options in the next available multi-box. This way I wouldn’t have to create a new line in the jquery code for the new box.
Rather than basing it on position (the next available multi-box), I would use a data attribute to store the id of the relevant multi-box.
Then in your script: