Filter users by data-attribute Jquery - javascript

I am trying to filter users by its data attribute , I have main div called user-append which contains users that I get from ajax get request , there can be 3 users or 100 users, its dynamical , this is my div with one user for the moment
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="'+user.profesion+'" id="user_'+user.id+'" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="'+user.id+'" id="user_'+ user.id + '_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" width="100%" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
<p class="fullName dataText">'+user.fullName+'</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">'+user.employee_id+'</p>
</div>
</div>
</div>
</div>
</div>
as you can see I have data-profesion attribute from which I am trying to filter users depend on the profession that they have , I get the ajax request like this
$.ajax({
url: "/rest/users",
success: function (users) {
var options = [];
$user = $("#append_users");
$.each(users, function (i, user) {
options.push({
'profession': user.prof.Profession,
'gender': user.prof.Gender
});
userArr.push({
'id': user.id,
'firstName': user.prof.FirstName,
'lastName': user.prof.LastName,
'fullName': user.prof.FirstName + ' ' + user.profile.LastName,
'email': user.email,
'avatar': user.prof.Photo,
'profesion': user.prof.Profession
});
$('#filterByProfession').html('');
$('#filterByGender').html(''); // FIRST CLEAR IT
$.each(options, function (k, v) {
if (v.profession !== null) {
$('#filterByProfession').append('<option>' + v.profession + '</option>');
}
if (v.gender !== null) {
$('#filterByGender').append('<option>' + v.gender + '</option>');
}
});
});
});
and now I am trying to filter the users by its data-profesion, on change of my select option which I populate from the ajax get request , It should show only the users that contain that data-profesion value , something like this
$('#filterByProfession').change(function () {
var filterVal = $(this).val();
var userProfVal = $(".fc-event").attr("data-profesion");
if (filterVal !== userProfVal) {
}
});

You can use a CSS selector to find those users, and then hide them:
$('#filterByProfession').change(function () {
// first hide ALL users
$('.draggable-user').hide()
// then filter out the ones with the correct profession:
// (you need to escape the used quote)
.filter('[data-profesion="' + $(this).val().replace(/"/g, '\\"') + '"]')
// ... and show those
.show();
});

You're trying to get the userProfVal throughout a className selector which can return more than one element.
var userProfVal = $(".fc-event").attr("data-profesion");
^
Use the jQuery function .data() to get data attributes.
Look at this code snippet using the .each to loop over all elements returned by this selector .fc-event:
$('#filterByProfession').change(function() {
var filterVal = $(this).val();
$(".fc-event").hide().each(function() {
if ($(this).data("profesion") === filterVal) {
$(this).show();
}
});
});
Example with static data
$('#filterByProfession').change(function() {
var filterVal = $(this).val();
$(".fc-event").hide().each(function() {
if ($(this).data("profesion") === filterVal) {
$(this).show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='filterByProfession'>
<option>-----</option>
<option>Developer</option>
<option>Cloud computing</option>
</select>
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="Developer" id="user_1" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="1" id="user_1_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
Developer
<p class="fullName dataText">Ele</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">11</p>
</div>
</div>
</div>
</div>
</div>
<div id="user-append">
<div class="fc-event draggable-user" data-profesion="Cloud computing" id="user_2" style="z-index: 9999;">
<div class="container-fluid">
<input type="hidden" value="2" id="user_2_value" class="userId">
<div class="row" style="justify-content: center;">
<div class="col-xs-3 avatar-col">
<div class="innerAvatarUserLeft">
<img src="'+getUserImage(user.avatar)+'" style="margin: 0 auto;">
</div>
</div>
<div class="col-xs-9 data-col">
Cloud computing
<p class="fullName dataText">Enri</p>
<p class="usr_Gender dataText">Male</p>
<div style="position: relative">
<li class="availableUnavailable"></li>
<li class="usr_profesion dataText">AVAILABLE</li>
</div>
<p class="user_id" style="float:right;margin: 3px">11</p>
</div>
</div>
</div>
</div>
</div>
See? the sections are being hidden according to the selected option.

Try using this
$(".fc-event[data-profesion='" + filterVal + "']").show();
$(".fc-event[data-profesion!='" + filterVal + "']").hide();

Related

Image filter Navigation

I have all the code and seems okay to me but when I click on the navigation links the link is directed to index.html or the landing project. How do I make the links filter the images?
This is the Javascript and html
$(document).ready(function() {
$(".button").click(function() {
var name = $(this).attr("data-filter");
if (name == "all") {
$(".filter").show("2000");
} else {
$(".filter").not("." + name).hide("2000");
$(".filter").filter("." + name).show("2000");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="portfolio">
<div style="text-align: center">
<div class="navigation">
ALL
ONE
TWO
THREE
</div>
<div class="ImageContainer">
<div class="filter one">
<img src="img/beach.jpg" width="400px" height="250px">
</div>
<div class="filter one">
<img src="img/Windows.jpg" width="400px" height="250px">
</div>
I expected my images to filter but they navigation links are not working
You need to prevent the default action of the link and also change your numbers to numbers (remove the quotes around the 2000)
$(document).ready(function() {
$(".button").click(function(e) { // pass the event back into the function
e.preventDefault(); // prevent the link action
var name = $(this).attr("data-filter");
if (name == "all") {
$(".filter").show(2000); // remove quotes
} else {
$(".filter").not("." + name).hide(2000);
$(".filter").filter("." + name).show(2000);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="portfolio">
<div style="text-align: center">
<div class="navigation">
ALL
ONE
TWO
THREE
</div>
<div class="ImageContainer">
<div class="filter one">
<img src="img/beach.jpg" width="400px" height="250px">
</div>
<div class="filter one">
<img src="img/Windows.jpg" width="400px" height="250px">
</div>

searchbar alert when there is no match jQuery

I made simple searchbar for my app. Right now it searching the users by data attribute but when it doesn't find any match it display nothing. I want it to show error message when there is no match. I made if statement but it only display when I type something into input and delete it. How to display error message immediately when searchbar doesn't find any user.
JS
$(document).ready(function () {
// Pokaż/Ukryj wyszukiwarkę
$('.show-hide-search-bar').on('click', function () {
if ($('.searcher-section').is(":visible")) {
$('.searcher-section').hide("slide");
$('.show-hide-search-bar').text('Pokaż Wyszukiwarkę');
} else {
$('.searcher-section').show("slide");
$('.show-hide-search-bar').text('Ukryj Wyszukiwarkę');
}
});
// Zmiana tekstu w zależności od pojawienia się searchera
if ($('#agents').length > 0) {
$('#label-searchbar').html('Imię, Nazwisko, Adres email');
$('#input-searchbar').attr('placeholder', 'Podaj imię, nazwisko lub adres email');
} else if ($('#company').length > 0) {
$('#label-searchbar').html('Nazwa biura');
$('#input-searchbar').attr('placeholder', 'Podaj nazwę biura');
}
//Dynamiczne wyszukiwanie .card dla agentów | .clearfix dla listy
$('.searcher-input').keyup(function (event) {
$('.null-data').hide();
if ($(this).val()) {
var input = $(this).val();
var trimmedInput = input.trim();
var terms = input.split(/\W+/g);
$(".card").hide();
$(".clearfix.alt").hide();
$(".card[data-agent*='" + trimmedInput + "' i]").show();
$(".clearfix[data-name*='" + trimmedInput + "' i]").show();
// $(".card[data-lastname*='" + trimmedInput + "']").show();
// $(".card[data-lastname*='" + trimmedInput + "'][data-firstname*='" + trimmedInput + "']").show();
// $(".card[data-email*='" + trimmedInput + "']").show();
$(".col-xs-12").css("min-height", "0");
$(".col-md-4").css("min-height", "0");
$(".col-sm-5").css("min-height", "0");
if ($('.card').is(':visible').get(0)) {
$('.null-data').show(function () {
$(this).effect("shake");
});
}
if (!$('.clearfix').is(':visible').get(0)) {
$('.null-data').show(function () {
$(this).effect("shake");
});
}
} else {
$(".clearfix.alt").show();
$(".card").show();
$('.null-data').show(function () {
$(this).effect("shake");
});
}
});
});
HTML
<div class="container">
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="searcher-section" style="display: none">
<div class="show-hide-searcher">
<div class="input-section">
<div class="label-input-searcher">
<label for="" class="searcher-label" id="label-searchbar"></label>
<input type="text" placeholder=""
class="searcher-input form-control" id="input-searchbar"/>
<div class="null-data" style="display: none;">Wprowadź poprawne dane</div>
</div>
</div>
</div>
</div>
</div>
<div class="show-hide-section">
<button class="btn btn-success show-hide-search-bar" id="searchbar-button">Pokaż wyszukiwarkę</button>
</div>
</div>
</div>
<div class="container">
<div class="row">
<h3 class="title" id="agents">Doradcy</h3>
<div class="cards">
#foreach($agents as $agent)
<div class="col-xs-12 col-sm-5 col-md-4">
<div class="card" data-agent="{{$agent->firstname}} {{$agent->lastname}} {{$agent->email}}">
<figure>
<div class="img-ref">
<a href=""
class="">
#if(isset($agent->has_avatar) && $agent->has_avatar !== 0)
<div style="background: url(''); background-size: cover;" class="photo"></div>
#else
<div style="background: url(''); background-size: cover;"
class="photo"></div>
#endif
</a>
</div>
<ul>
<li>
<a href=""
class="teamLink agent-color">
<h3 class="agent-name">{{$agent->firstname}} {{$agent->lastname}}</h3> </a>
</li>
</ul>
#if(isset($agent->company_name))
<div class="teams-summary">
{{$agent->company_name}}
</div>
#endif
<div class="contact-position">
{{--telefon kontaktowy--}}
<div class="mobile-info card-contact-info">
{{$agent->phone}}
</div>
{{--adres mailowy--}}
<div class="email-info card-contact-info">
{{$agent->email}}
</div>
</div>
</figure>
</div>
</div>
#endforeach
</div>
{{----}}
</div>
</div>
check element length
........
$(".clearfix.alt").hide();
if($(".card[data-agent*='" + trimmedInput + "' i]").length == 0) {
alert("no result");
return;
}
$(".card[data-agent*='" + trimmedInput + "' i]").show();
....

Knockout.js : ObservableArray with ObservableArrays inside?

I'm using this plugin called Dragula which needs an ObservableArray as a source for the data..
HTML/Knockout-bindings
<div class="widget-container">
<div class="widget-content visible" id="team-setup">
<div class="header">
<p>Lagoppsett</p>
<p></p>
</div>
<div class="col-sm-12">
<div class="row">
<div class="widget-container">
<div class="col-xs-6 widget-content visible">
<div class="header">
<p>Tilgjengelige spillere</p>
<p></p>
</div>
<div class="player-card-container-mini" data-bind="dragula: { data: availablePlayers, group: 'playerz' } ">
<div class="player-card-mini">
<div class="player-card-left">
<div class="player-avatar" style="margin-left: 85%;">
<img src="Content/Images/player-female.png" id="imgAvatar" runat="server" />
<div class="player-shirt-no" data-bind="text: ShirtNo"></div>
</div>
</div>
<div class="player-card-subtext">
<div class="player-text">
<div class="player-card-header-small" data-bind="text: PlayerName"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-6 widget-content visible">
<div class="header">
<p>Lag</p>
<p></p>
</div>
<div data-bind="foreach: teamsetup">
<div data-bind="foreach: SubTeams">
<h1 data-bind="text: TeamSubName"></h1>
<div class="player-card-container-mini" data-bind="dragula: { data: Players, group: 'playerz' } " style="border: 1px solid red; min-height:200px">
<div class="player-card-mini">
<div class="player-card-left">
<div class="player-avatar" style="margin-left: 85%;">
<img src="Content/Images/player-female.png" id="img1" runat="server" />
<div class="player-shirt-no" data-bind="text: ShirtNo"></div>
</div>
</div>
<div class="player-card-subtext">
<div class="player-text">
<div class="player-card-header-small" data-bind="text: PlayerName"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div style="clear:both"> </div>
</div>
</div>
Knockout code :
var TeamSetupViewModel = function () {
var self = this;
self.teamsetup = ko.observableArray();
self.availablePlayers = ko.observableArray();
self.testPlayers = ko.observableArray();
}
var model = new TeamSetupViewModel();
ko.applyBindings(model, document.getElementById("team-setup"));
var uri = 'api/MainPage/GetTeamSetup/' + getQueryVariable("teamId");
$.get(uri,
function (data) {
model.teamsetup(data);
model.availablePlayers(data.AvailablePlayers);
model.testPlayers(data.AvailablePlayers);
console.log(data);
}, 'json');
});
The problem is... that i'm having a ObservableArray at the top node, and i do need ObservableArrays further down in the hierarchy.
model.availablePlayers works fine, but when accessing the other players in the html/ko foreach loops through teamsetup -> SubTeams -> Players it doesn't work due to Players isn't an ObservableArray. (There might be everyting from 1 to 7 SubTeams with players).
So how can i make the Players in each SubTeams an ObservableArray ?
See the image for the datastructure :
You could use Mapping plugin, but if players is the only thing you need, you can do it manually:
Simplify your view model:
var TeamSetupViewModel = function () {
var self = this;
self.availablePlayers = ko.observableArray();
self.subTeams = ko.observableArray();
}
After you get the data from the server, populate the view model converting the array of players on every team to an observable array of players:
$.get(uri,
function (data) {
model.availablePlayers(data.AvailablePlayers);
model.subTeams(data.SubTeams.map(function(t) { t.Players = ko.observableArray(t.Players); return t; }));
}, 'json');
});
Finally, remove the following line in your template (with its closing tag) - nothing to iterate over anymore:
<div data-bind="foreach: teamsetup">
... and update the name of the property in the next line, so it is camel case like in the VM:
<div data-bind="foreach: subTeams">

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

How can I group divs and calculate values?

I have the next structure:
<div class="container">
<div class="block">
<div class="id">1</div>
<div class="date">02/21/2015</div>
<div class="value">111</div>
</div>
<div class="block">
<div class="id">1</div>
<div class="date">02/21/2015</div>
<div class="value">222</div>
</div>
<div class="block">
<div class="id">1</div>
<div class="date">02/30/2015</div>
<div class="value">333</div>
</div>
<div class="block">
<div class="id">1</div>
<div class="date">02/30/2015</div>
<div class="value">444</div>
</div>
<div class="block">
<div class="id">2</div>
<div class="date">05/17/2015</div>
<div class="value">555</div>
</div>
</div>
I need group it and calculate values, then I need print this in my page.
Steps:
Group by ID
Group by Date (in ID)
Calculate Values (in each Date)
So, the result:
<div class="container">
<div class="block">
<div class="id">1</div>
<div class="date">02/21/2015</div>
<div class="value">333</div> <!-- 111+222 -->
</div>
<div class="block">
<div class="id">1</div>
<div class="date">02/30/2015</div>
<div class="value">777</div> <!-- 333+444 -->
</div>
<div class="block">
<div class="id">2</div>
<div class="date">05/17/2015</div>
<div class="value">555</div>
</div>
</div>
P.S. Of course, I don't need in comments. :)
Can you help me with JS/jQ code?
This is one way (demo):
var $container = $('.container'),
$blocks = $container.find('.block'),
results = {},
output = '';
$blocks.each(function () {
var $this = $(this),
id = $this.find('.id').html(),
date = $this.find('.date').html(),
value = $this.find('.value').html();
results[id] = results[id] || {};
results[id][date] = results[id][date] || 0;
results[id][date] += parseInt(value);
});
$.each(results, function (id, dates) {
$.each(dates, function (date, value) {
output += '<div class="block">' +
'<div class="id">' + id + '</div>' +
'<div class="date">' + date + '</div>' +
'<div class="value">' + value + '</div>' +
'</div>';
});
});
$container.html(output);

Categories