Filtering a property with multiple values for one field - List.js and Filter.js

I am currently using the list.js plugin along with it's filter extension to produce a search results page that allows the user to filter down the end results to make it easier for them to find exactly what they are looking for.

I have been using their API to try and come up with a solution but in all honesty it is a little dated and not sure when it was last updated.

http://www.listjs.com/docs/list-api

My code is as follows:

HTML

<div id="search-results"> <div class="col-md-3"> <div class="panel panel-warning"> <div class="panel-heading">Filters</div> <div class="panel-body"> <div class="search-filter"> <ul class="list-group"> <li class="list-group-item"> <div class="list-group-item-heading"> <h4>Filter Options</h4> </div> </li> <li class="list-group-item"> <div class="nameContainer"> <h5 class="list-group-item-heading">Name</h5> </div> </li> <li class="list-group-item"> <div class="typeContainer"> <h5 class="list-group-item-heading">Type</h5> </div> </li> <li class="list-group-item"> <div class="difficultyContainer"> <h5 class="list-group-item-heading">Difficulty</h5> </div> </li> <li class="list-group-item"> <label>Tour contains</label> <input class="search form-control" placeholder="Search" /> </li> </ul> </div> </div> </div> </div> <div class="col-md-9"> <div class="panel panel-primary"> <div class="panel-heading">Results</div> <div class="list panel-body"> <div class="package well"> <div class="name">Niagra Falls</div> <div class="type hidden">Boat Trip</div> <div class="difficulty">Relaxed</div> </div> <div class="package well"> <div class="name">Pyramids</div> <div class="type hidden">History Holiday</div> <div class="difficulty">Relaxed</div> </div> <div class="package well"> <div class="name">Great Barrier Reef</div> <div class="type hidden">Snorkling Holiday</div> <div class="difficulty">Dangerous</div> </div> <div class="package well"> <div class="name">Boar Hunting</div> <div class="type hidden">Hunting Trip</div> <div class="difficulty">Active</div> </div> <div class="package well"> <div class="name">Thames Cruise</div> <div class="type hidden">Cruise</div> <div class="difficulty">Easy</div> </div> </div> <ul class="pagination"></ul> </div> </div> </div>

Javascript

var options = { valueNames: ['name', 'type', 'difficulty'], page: 3, plugins: [ ListPagination({}) ] }; var userList = new List('search-results', options); var updateList = function () { var name = new Array(); var type = new Array(); var difficulty = new Array(); $("input:checkbox[name=name]:checked").each(function () { name.push($(this).val()); }); $("input:checkbox[name=type]:checked").each(function () { type.push($(this).val()); }); $("input:checkbox[name=difficulty]:checked").each(function () { difficulty.push($(this).val()); }); var values_type = type.length > 0 ? type : null; var values_name = name.length > 0 ? name : null; var values_difficulty = difficulty.length > 0 ? difficulty : null; userList.filter(function (item) { return (_(values_type).contains(item.values().type) || !values_type) && (_(values_name).contains(item.values().name) || !values_name) && (_(values_difficulty).contains(item.values().difficulty) || !values_difficulty) }); } userList.on("updated", function () { $('.sort').each(function () { if ($(this).hasClass("asc")) { $(this).find(".fa").addClass("fa-sort-alpha-asc").removeClass("fa-sort-alpha-desc").show(); } else if ($(this).hasClass("desc")) { $(this).find(".fa").addClass("fa-sort-alpha-desc").removeClass("fa-sort-alpha-asc").show(); } else { $(this).find(".fa").hide(); } }); }); var all_type = []; var all_name = []; var all_difficulty = []; updateList(); _(userList.items).each(function (item) { all_type.push(item.values().type) all_name.push(item.values().name) all_difficulty.push(item.values().difficulty) }); _(all_type).uniq().each(function (item) { $(".typeContainer").append('<label><input type="checkbox" name="type" value="' + item + '">' + item + '</label>') }); _(all_name).uniq().each(function (item) { $(".nameContainer").append('<label><input type="checkbox" name="name" value="' + item + '">' + item + '</label>') }); _(all_difficulty).uniq().each(function (item) { $(".difficultyContainer").append('<label><input type="checkbox" name="difficulty" value="' + item + '">' + item + '</label>') }); $(document).off("change", "input:checkbox[name=type]"); $(document).on("change", "input:checkbox[name=type]", updateList); $(document).off("change", "input:checkbox[name=name]"); $(document).on("change", "input:checkbox[name=name]", updateList); $(document).off("change", "input:checkbox[name=difficulty]"); $(document).on("change", "input:checkbox[name=difficulty]", updateList);

I've also created a working example on Codepen.

http://codepen.io/JasonEspin/pen/bdajKo

What I wish to achieve is for some packages, they may have multiple type values such as:

<div class="package well"> <div class="name">Niagra Falls</div> <div class="type hidden">Boat Trip</div> <div class="type hidden">Other trip type</div> <div class="difficulty">Relaxed</div> </div>

So in this situation, I would expect my filter to detect that there is a type of Boat Trip and Other trip type and display these options as a filter option. If either is selected, this package is then returned. However, it seems to ignore the second type.

I have even tried it like this as I expected it to act like an array but this was not the case. It just mashed the two items together to create a random option.

<div class="package well"> <div class="name">Niagra Falls</div> <div class="type hidden"><div>Boat Trip</div><div>Other Trip Type</div> </div> <div class="difficulty">Relaxed</div> </div>

So, does anyone have any ideas how I can adapt my code to accept multiple options? My ideal scenario would be for me to attach a number of departure dates to each package and enable the user to filter by these departure dates.

Any help would be greatly appreciated as I believe the issue may be with my Lodash code but as it is my first time using Lodash i'm a little bit unsure of what it is actually doing due to its unusual syntax.

-------------Problems Reply------------

This was actually fairly straightforward to implement using a combination of string.split() definitions and array concatenations.

HTML

<div id="search-results">
<div class="col-md-3">
<div class="panel panel-warning">
<div class="panel-heading">Filters</div>
<div class="panel-body">
<div class="search-filter">
<ul class="list-group">
<li class="list-group-item">
<div class="list-group-item-heading">
<h4>Filter Options</h4>
</div>
</li>
<li class="list-group-item">
<div class="nameContainer">
<h5 class="list-group-item-heading">Name</h5>
</div>
</li>
<li class="list-group-item">
<div class="typeContainer">
<h5 class="list-group-item-heading">Type</h5>
</div>
</li>
<li class="list-group-item">
<div class="difficultyContainer">
<h5 class="list-group-item-heading">Difficulty</h5>
</div>
</li>
<li class="list-group-item">
<label>Tour contains</label>
<input class="search form-control" placeholder="Search" />
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="col-md-9">
<div class="panel panel-primary">
<div class="panel-heading">Results</div>
<div class="list panel-body">
<div class="package well">
<div class="name">Niagra Falls</div>
<div class="type hidden">Boat Trip|Other Trip|My Trip</div>
<div class="difficulty">Relaxed</div>
</div>
<div class="package well">
<div class="name">Pyramids</div>
<div class="type hidden">History Holiday</div>
<div class="difficulty">Relaxed</div>
</div>
<div class="package well">
<div class="name">Great Barrier Reef</div>
<div class="type hidden">Snorkling Holiday</div>
<div class="difficulty">Dangerous</div>
</div>
<div class="package well">
<div class="name">Boar Hunting</div>
<div class="type hidden">Hunting Trip</div>
<div class="difficulty">Active</div>
</div>
<div class="package well">
<div class="name">Thames Cruise</div>
<div class="type hidden">Cruise</div>
<div class="difficulty">Easy</div>
</div>
</div>
<ul class="pagination"></ul>
</div>
</div>
</div>

JAVASCRIPT

var options = {
valueNames: ['name', 'type', 'difficulty'],
page: 3,
plugins: [
ListPagination({})
]
};
var userList = new List('search-results', options);
var updateList = function () {
var name = new Array();
var type = new Array();
var difficulty = new Array();

$("input:checkbox[name=name]:checked").each(function () {
name.push($(this).val());
});

$("input:checkbox[name=type]:checked").each(function () {
if($(this).val().indexOf('|') > 0){
var arr = $(this).val().split('|');
var arrayLength = arr.length;
type = type.concat(arr);
console.log('Multiple values:' + arr);
}else{
type.push($(this).val());
console.log('Single values:' + arr);
}
});

$("input:checkbox[name=difficulty]:checked").each(function () {
difficulty.push($(this).val());
});

var values_type = type.length > 0 ? type : null;
var values_name = name.length > 0 ? name : null;
var values_difficulty = difficulty.length > 0 ? difficulty : null;

userList.filter(function (item) {
var typeTest;
var nameTest;
var difficultyTest;

if(item.values().type.indexOf('|') > 0){
var typeArr = item.values().type.split('|');
for(var i = 0; i < typeArr.length; i++){
if(_(values_type).contains(typeArr[i])){
typeTest = true;
}
}
}

return (_(values_type).contains(item.values().type) || !values_type || typeTest)
&& (_(values_name).contains(item.values().name) || !values_name)
&& (_(values_difficulty).contains(item.values().difficulty) || !values_difficulty)
});
}

userList.on("updated", function () {
$('.sort').each(function () {
if ($(this).hasClass("asc")) {
$(this).find(".fa").addClass("fa-sort-alpha-asc").removeClass("fa-sort-alpha-desc").show();
} else if ($(this).hasClass("desc")) {
$(this).find(".fa").addClass("fa-sort-alpha-desc").removeClass("fa-sort-alpha-asc").show();
} else {
$(this).find(".fa").hide();
}
});
});

var all_type = [];
var all_name = [];
var all_difficulty = [];

updateList();

_(userList.items).each(function (item) {
if(item.values().type.indexOf('|') > 0){
var arr = item.values().type.split('|');
all_type = all_type.concat(arr);
}else{
all_type.push(item.values().type)
}

all_name.push(item.values().name)
all_difficulty.push(item.values().difficulty)
});

_(all_type).uniq().each(function (item) {
$(".typeContainer").append('<label><input type="checkbox" name="type" value="' + item + '">' + item + '</label>')
});

_(all_name).uniq().each(function (item) {
$(".nameContainer").append('<label><input type="checkbox" name="name" value="' + item + '">' + item + '</label>')
});

_(all_difficulty).uniq().each(function (item) {
$(".difficultyContainer").append('<label><input type="checkbox" name="difficulty" value="' + item + '">' + item + '</label>')
});

$(document).off("change", "input:checkbox[name=type]");
$(document).on("change", "input:checkbox[name=type]", updateList);
$(document).off("change", "input:checkbox[name=name]");
$(document).on("change", "input:checkbox[name=name]", updateList);
$(document).off("change", "input:checkbox[name=difficulty]");
$(document).on("change", "input:checkbox[name=difficulty]", updateList);

Codepen

http://codepen.io/JasonEspin/pen/bdajKo

Category:javascript Views:20 Time:2019-03-17

Related post

  • Rails - find_by_sql - Querying with multiple values for one field 2010-11-18

    I'm having trouble joining the values for querying multiple values to one column. Here's what I got so far: def self.showcars(cars) to_query = [] if !cars.empty? to_query.push cars end return self.find_by_sql(["SELECT * FROM cars WHERE car IN ( ? )"]

  • Multiple values for one field with Comma-separated Values .csv format 2010-10-04

    Is it possible to have multiple values under the same field in a .CSV file? Lets say I have a "email" field on my webpage, and the user may optionally type in multiple addresses. Then I want my .csv file to be able to handle a unknown number of "emai

  • Multiple values for one field 2012-03-22

    In GXT I want to create a form where a single field can have multiple values. so once one value is provided user should have option enter another value for the same field, similar to how we attach files in an e-mail.. what is the best way to do this?

  • Listing multiple values for one field on a report 2014-07-05

    I have a query that gives the following output; Record Type Color Name 34 Veg Red Pepper 34 Veg Red Tomato 42 Veg Green Pea 42 Veg Green Lettuce 42 Veg Green Cumcumber 46 Veg Green Onion 46 Veg Green Asparagus In a report, I would like to be able to

  • countifs function with multiple values for one condition 2014-05-27

    I am trying to summarize some data by week for 2 different groups. I have my data in a different worksheet in my workbook and am trying to come up with a table in a different tab which shows the count by week for each of the 2 groups. I can count bas

  • Processing multiple values for one single option using getopt/optparse? 2010-11-05

    Is it possible to fetch multiple values for one option using getopt or optparse, as shown in the example below: ./hello_world -c arg1 arg2 arg3 -b arg4 arg5 arg6 arg7 Please note that the number of actual values for each option (-c, -b) could be eith

  • Multiple validators for one field. JSF 2010-07-14

    Can you apply multiple validators for one field. i.e: <ice:inputText id="tawjihiAvg" maxlength="5" partialSubmit="true" style="left: 0px; top: 144px; position: absolute; width: 144px" title="#{msg.Tawjihi_Average}" value="#{SessionBean1.tawjihiAvg

  • storing multiple values in one field 2011-06-26

    I want users to be able to select their majors. For example, person A could select computer science, mathematics, and history as his majors. Users can select any number of majors. I have a list of organizations in my database that would only accept s

  • Proper sql table structure with multiple values of a field 2011-12-05

    I have been working with some basic sql databases and am designing an application and am wondering about having multiple values in 1 field. I am used to a relational DB model and am wondering if sql supports this. Here is an example delimited record:

  • How do I query for records with multiple values for the last column in a compound GROUP BY clause? 2009-09-23

    Given data that looks similar to this: +---------+-----------+----------+ | country | city | district | +---------+-----------+----------+ | Japan | Tokyo | 1 | | Japan | Tokyo | 1 | | Japan | Tokyo | 2 | | China | Shanghai | A | | China | Shanghai |

  • How to configure defaults for a parameter with multiple values for a Maven plugin 2009-11-02

    I'm writing a Maven plugin and I am using default values for all parameters such as this: /** * The file with the site structure. * * @parameter expression="${generateSite.siteFile}" default-value="${basedir}/src/oda/site.xml" */ private File siteFil

  • SQL Query with multiple values in one column 2010-05-10

    I've been beating my head on the desk trying to figure this one out. I have a table that stores job information, and reasons for a job not being completed. The reasons are numeric,01,02,03,etc. You can have two reasons for a pending job. If you selec

  • Using multiple values for one key in appSettings 2010-11-18

    I'm learning about how to use config files and I ran into some problems that I'm hoping someone here can give me some advice. It doesn't matter if my files are XML or not but the majority of examples I have read are using them and Im all for anything

  • append multiple values for one key in Python dictionary 2010-07-07

    I am new to python and I have a list of years and values for each year. What I want to do is check if the year already exists in a dictionary and if it does, append the value to that list of values for the specific key. So for instance, I have a list

  • Sending POST request with multiples values for same key with requests library 2011-12-06

    How would you go about sending a request with multiples values with the same key? r = requests.post('http://www.httpbin.org/post', data={1: [2, 3]}) print r.content { ... "form": { "1": "3" }, ... } Edit: Hmm, very odd. I tried echoing the post data

  • Multiple results for one field in a joined SQL query 2010-02-26

    I'm not sure if this is possible from with a SQL query, but I'll give it a go. I'm developing a SharePoint web part in C# that connects to a SQL database and runs a query, then databinds that result set to a gridview. It's working fine, but I have a

  • How can i show suggestions for multiple values for edittext field in android? 2011-07-11

    I need a functionality in android app, that is similar to Gmail app in android real device which has drop down suggestions for multiple value in "To" field or like stack overflow's tag suggestions for multiple values. For example, I entered a email a

  • run a function with multiple values for more than one arguments that are not the first ones 2010-12-08

    In R, if I have a function myfun<-function(ys, T, N, beta, gamma, sigma) {...} where beta and gamma are scalars. If I have fixed values for ys, T, N, and sigma, but a vector of values of beta and a vector of values for gamma, is it possible to run

  • How do I select a cell with multiple values in one column? 2010-08-17

    I have an MYSQL table with a large product list. In this product list table there are categories, a name, description, text, etc. I want to add a modifier for the industries that it can be used in (e.g. hospitals, schools, events, sport events, etc.)

  • Compare one String with multiple values in one expression 2012-04-18

    I have one String variable, str with possible values, val1, val2 and val3. I want to compare (with equal case) str to all of these values using an if statement, for example: if("val1".equalsIgnoreCase(str)||"val2".equalsIgnoreCase(str)||"val3.equalsI

  • Python 2.7.2 Multiple Values for one variable 2012-02-08

    I run my own business from home and started use Python 2 days ago. I'm trying to write a script that will search through my log files line by line and tell me if a system doesn't match my mandatory naming scheme. There are multiple different schemes

  • Multiple values for one coloum php and sql 2014-06-09

    I am new to sql and php And maybe i don't understand what you will answer so please explain it fully that I can understand so here's my question Now i have 5 coloumns Id,Name,UserName,Password,valuie you can understand 4 coloumns the fifth is valuie

  • Complex find statement, don't know how to write multiple values for one condition 2012-03-08

    I am trying to build a paginated find call to my Unit model. I need the condition to be that it looks for unit.type of condo and rentalco, house and rentalco, but NOT rentalco and hotel. Additionally, the way I have my code worded, cake only returns

  • PHP MySQL Searching multiple values in one field 2010-12-17

    How can I store multiple values in a single SQL field and ensure this data is searchable? For example I want to be able to do this name | num ----------- John | 21, 22, 34 Mike | 41, 32, 43 Dave | 12, 23, 34 $query = SELECT name from table WHERE num

  • Storing multiple values in one field (IDs of images liked by user) 2011-12-27

    I have a site that allows users to vote on images. Each image has a unique id number. For voting restriction purposes, I'd like to keep track of what each user has liked. How would I go about setting up a row in the USERS table that holds all the dif

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.178 (s). 12 q(s)