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