2011-05-27 119 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> 
相關問題