I'm trying to filter by select dropdown using List.js
My example is working fine with radio buttons. But I would like to replace them with a select list.
I tried changing this html
<label>
<input class="filter" type="radio" value="Blvd" name="address" id="address-all" /> Boulevard
</label>
<label>
<input class="filter" type="radio" value="Blvd" name="address" id="address-boulevard" /> Boulevard
</label>
to this
<select>
<option class="filter-all" type="radio" value="all" name="address" id="address-all" selected>
All
</option>
<option class="filter" type="radio" value="Blvd" name="address" id="address-boulevard">Boulevard
</option>
</select>
and changed all instances of checked to selected in the .js
var options = {
valueNames: [
'name',
'address',
],
};
var userList = new List('users', options);
function resetList() {
userList.search();
userList.filter();
userList.update();
$(".filter-all").prop('selected', true);
$('.filter').prop('selected', false);
$('.search').val('');
};
function updateList() {
var values_address = $("input[name=address]:selected").val();
console.log(values_address);
userList.filter(function(item) {
var addressFilter = false;
if (values_address == "all") {
addressFilter = true;
} else {
addressFilter = item.values().address.indexOf(values_address) >= 0;
}
return addressFilter
});
userList.update();
}
$(function() {
$('input[name=address]').change(updateList);
userList.on('updated', function(list) {
if (list.matchingItems.length > 0) {
$('.no-result').hide()
} else {
$('.no-result').show()
}
});
});
But so far this isn't working. Thanks for any help with this.
Here is a fiddle with the original code: https://jsfiddle.net/6tht5pyk/
See this forked fiddle: https://jsfiddle.net/7pkq23ty/
Simply change the selector from $("input[name=address]:selected").val();
to var values_address = $("select").val();
And off course bind the event to the select
element: $('select').change(updateList);
And it goes without saying that it's recommended to add an ID to your select
element and using it in your selectors, instead of using $('select')
- I used it to make the least amount of changes to your code.