jQuery 选择所有下一个多选框中的选项

4
我有几个表格需要使用一些多选框(附属公司列表、来源列表、产品列表等)。每个表格都可以拥有自己的一组多选框,以满足客户需求。
我还创建了一个链接,允许用户“选择所有”多选框中的选项。目前看来一切运行良好!但我想让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类的单击事件,但要聪明地选择下一个可用的多选框中的所有选项。这样我就不必为新的框创建jquery代码中的新行。

2个回答

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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接