dongle7882 2015-12-22 20:55
浏览 6
已采纳

多个选定值的jQuery值

I have the following code for a multi select list. It works when one item is selected at a time. I want to make it work when I select more than item.

enter image description here

<select name="size1" multiple="multiple" id="ddYear"
        class="form-control input-sm">
<option value="">Select Manufacturers</option>
<?php
   $record = mysqli_query($con
          "SELECT DISTINCT Manufacturer
           FROM db
           WHERE Manufacturer in ('A', 'B', 'C', 'D', 'E', 'F')
           ORDER BY Manufacturer ASC");
   while ($row = mysqli_fetch_array($record)) {
      echo "<option value='" . $row['Manufacturer'] . "'>"
           . $row['Manufacturer'] . "</option>";
   }
?>
</select>

Js code

 <script type="text/javascript">
   var $rows = $('#dataTables-example2 tbody tr');
   $('#ddYear').change(function() {
     var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
     $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
     }).hide();
   });
</script>

It works with one item selected (the matching table rows are shown), but when I select two items, it hides all rows from my table (nothing matches). Instead I would like to see the rows that match with one of the selected items.

  • 写回答

1条回答 默认 最新

  • doumei9832 2015-12-22 21:27
    关注

    jQuery returns a comma-separated list of values when you have more than one element selected, so a quick solution would be to create a regular expression to search by, and replace those commas by pipes (the reg ex OR operator).

    This way, your code only needs minor changes:

    // create reg exp with pipes:
    var val = new RegExp($.trim($(this).val()).replace(/ +/g, ' ').toLowerCase()
            .replace(/,/g, '|'));
    $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.search(val); // use search for reg ex
    }).hide();
    

    Now, if the values in the list also contain commas you will get a search pattern that might match too many rows, but I think with this info you can make improvements if necessary.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 表达式必须是可修改的左值
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题