Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery select all options in next multi-select box

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.

like image 888
coffeemonitor Avatar asked Jan 20 '23 15:01

coffeemonitor


1 Answers

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.

<div class="selectAll" data-multi-id="sourceid">select all</div>

Then in your script:

<script language="javascript" type="text/javascript">
    $(document).ready(function(){  
        $(".selectAll").click(function(){    
            var multi = $(this).data('multi-id');
            $('#' + multi + ' option').attr('selected', 'selected');
        });
    });
</script>
like image 151
AaronShockley Avatar answered Jan 28 '23 20:01

AaronShockley