2011-05-27 203 views
4

我有几种需要使用几个多选框的形式。 (关联公司名单,来源清单,产品清单等)每种形式都可以有自己的一套多盒子,无论客户需要什么。jquery选择下一个多选框中的所有选项

我还创建了一个链接,允许用户“选择所有”在任何多选框中的选项。到目前为止,事情效果很好!但我想让jquery更聪明一些。

这里是我所编码的例子:

<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> 

这完全适用。但我倾向于为其他过滤原因添加更多的多方框。 我想让jquery检测.selectAll类的click事件,但要足够聪明才能在下一个可用的多选框中选择所有选项。这样我就不必在新盒子的jQuery代码中创建一个新行。

回答

6

而不是基于位置(下一个可用的多框),我会使用数据属性来存储相关多方框的ID。

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

然后在你的脚本:

<script language="javascript" type="text/javascript"> 
    $(document).ready(function(){ 
     $(".selectAll").click(function(){  
      var multi = $(this).data('multi-id'); 
      $('#' + multi + ' option').attr('selected', 'selected'); 
     }); 
    }); 
</script> 
3

对我来说,一个整洁的方法是将包裹<select multiple="multiple">框,它是在一个特定的父元素“全选”(如div),然后使用.parent()

<html> 
<head> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
</head> 
<body> 
    <div> 
    <span class="selectAll">Select all</span> 

    <select multiple="multiple"> 
     <option>1</option> 
     <option>2</option> 
    </select> 
    </div> 

    <div> 
    <span class="selectAll">Select all</span> 

    <select multiple="multiple"> 
     <option>1</option> 
     <option>2</option> 
    </select> 
    </div> 

    <span class="selectAll">Select really all</span> 

    <script> 
    $(".selectAll").click(function() { 
     $(this).parent().find('option').attr('selected','selected'); 
    }); 
    </script> 
</body> 
</html> 
相关问题