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();
....
Related
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();
i have a working load more button using bootstrap 3 but when i transition in bootstrap 4 i doesn't work anymore, and it's giving me a lot of headaches, i don't even have any error when i inspect the source code.
This is my html now in bootstrap 4
<div class="tab-pane active" id="starter" role="tabpanel">
<ul class ="starter-list text-center" id ="starter-list">
</ul>
<div id="loadMore"><button class ="load-btn btn btn-default">SEE MORE PARTS & ACCESSORIES</button></div>
</div>
this is my previously working js in bootstrap 3.
starter.forEach(function (current) {
var legend = current[0],
imgSrc = current[1],
descript = current[2],
descript2 = current[3],
descript3 = current[4],
price = current[5];
$('ul.starter-list').append(`
<li>
<div class = "row">
<div class="col col-md-12">
<div class="acs-detail">
<legend>` + legend + `</legend>
<img src="` + imgSrc + `" class="veh-content img-responsive" />
<div class="pna-description col-md-10">
<ul>
<p>` + descript + `</p>
<p>` + descript2 + `</p>
<p>` + descript3 + `</p>
</ul>
</div>
<div class="pna-price ">
<div class="text-deco">
<span>` + price + `</span>
</div>
<div class="border img-responsive">
<span></span>
</div>
</div>
</div>
</div>
</div>
</li>
`);
});
$(document).ready(function () {
var size_li = $(".starter-list li").size();
var x=6;
$('.starter-list li:lt('+x+')').show();
$('#loadMore').click(function () {
x= (x+3 <= size_li) ? x+3 : size_li;
$('#starter-list li:lt('+x+')').show();
if(x == size_li){
$('#loadMore').hide();
}
});
$('#showLess').click(function () {
x=(x-3<0) ? 3 : x-3;
$('#starter-list li').not(':lt('+x+')').hide();
$('#loadMore').show();
});
});
https://jsfiddle.net/zvgesa1x/
I'm trying to create on() mouseenter function for each element, but is there any way to shorten that function somehow. The problem is that I've created that on mouseenter function several times. Please help guys :)
This is the code below
var $member1 = $('.team-content img:nth-child(1)'),
$member2 = $('.team-content img:nth-child(2)'),
$member3 = $('.team-content img:nth-child(3)'),
$member4 = $('.team-content img:nth-child(4)')
$(".member1").on('mouseenter', function() {
$member1.css({
"left": "0px"
});
}).on('mouseleave', function() {
$member1.css({
"left": ""
});
});
$(".member2").on('mouseenter', function() {
$member2.css({
"left": "0px"
});
}).on('mouseleave', function() {
$member2.css({
"left": ""
});
});
$(".member3").on('mouseenter', function() {
$member3.css({
"left": "0px"
});
}).on('mouseleave', function() {
$member3.css({
"left": ""
});
});
$(".member4").on('mouseenter', function() {
$member4.css({
"left": "0px"
});
}).on('mouseleave', function() {
$member4.css({
"left": ""
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="team" class="about-team">
<div class="team-header">
<h2 class="team-text">Our Team</h2>
<div class="divider"></div>
</div>
<div class="section-content">
<div class="row text-center">
<div class="col-xs-6 col-md-3 col-lg-3 member1">
<h2 class="t-seperator">John Doe</h2>
<span>/CEO</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member2">
<h2 class="t-seperator">Jesica Ice</h2>
<span>/DESIGNER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member4">
<h2 class="t-seperator">Anna Moon</h2>
<span>/MARKETER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member3">
<h2 class="t-seperator">Michael Huge</h2>
<span>/DEVELOPER</span>
</div>
</div>
</div>
</div>
<div id="main-team" class="team-content">
<img src="assets/img/team/team1.jpeg" alt="Team 1">
<img src="assets/img/team/team2.jpg" alt="Team 2">
<img src="assets/img/team/team3.jpg" alt="Team 3">
<img src="assets/img/team/team4.jpg" alt="Team 4">
</div>
You can add a general handler and apply the function on the corresponding .member* element if you detect the index of the hovered img using the index() function, Here is an example: (In the example I change the color just for clarity)
$(".team-content img").on('mouseenter', function(e) {
var imageIndex = $(".team-content img").index(e.target) + 1;
$(".member" + imageIndex).css({
"color": "red"
});
}).on('mouseleave', function(e) {
var imageIndex = $(".team-content img").index(e.target) + 1;
$(".member" + imageIndex).css({
"color": "black"
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="team" class="about-team">
<div class="team-header">
<h2 class="team-text">Our Team</h2>
<div class="divider"></div>
</div>
<div class="section-content">
<div class="row text-center">
<div class="col-xs-6 col-md-3 col-lg-3 member1">
<h2 class="t-seperator">John Doe</h2>
<span>/CEO</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member2">
<h2 class="t-seperator">Jesica Ice</h2>
<span>/DESIGNER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member4">
<h2 class="t-seperator">Anna Moon</h2>
<span>/MARKETER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member3">
<h2 class="t-seperator">Michael Huge</h2>
<span>/DEVELOPER</span>
</div>
</div>
</div>
</div>
<div id="main-team" class="team-content">
<img src="assets/img/team/team1.jpeg" alt="Team 1">
<img src="assets/img/team/team2.jpg" alt="Team 2">
<img src="assets/img/team/team3.jpg" alt="Team 3">
<img src="assets/img/team/team4.jpg" alt="Team 4">
</div>
You can just use a loop to get them all done at once!
for (var i = 1; i <= 4; i++) {
$('.member' + i).on('mouseenter', function() {
$('.team-content img:nth-child(' + i + ')').css({'left': '0px'});
}).on('mouseleave', function() {
$('.team-content img:nth-child(' + i + ')').css({'left': ''});
});
}
I may have over-thought it, but if the member number and the nth-child number are the same, why not use that to create the relevant accessor? I've got three functions here: the first runs on initialization and saves the integer portion of the member number as a data attribute for later retrieval. The mouseenter and mouseleave functions retrieve that saved member number, and build the selector using that.
$("div[class*='member']").each(function() {
// for every member element, let's save its
// relevant nth-child number.
var myNumber = 0;
var myClasses = $(this).prop("class").split(" ");
// check all classes to find the member number
for (var i = 0; i <= myClasses.length; i++) {
if ( myClasses[i].startsWith("member") ) {
// strip out JUST the number portion.
myNumber = myClasses[i].match(/\d+/)[0];
}
if( myNumber != 0 )
break;
}
// Save the number portion for later.
$(this).data("nthNumber", myNumber);
}).on('mouseenter', function() {
// retrieve the saved number
var selector = ".team-content img:nth-child("+ $(this).data("nthNumber") +" )";
$(selector).show();
}).on('mouseleave', function() {
// retrieve the saved number
var selector = ".team-content img:nth-child("+ $(this).data("nthNumber") +" )";
$(selector).hide();
});
.about-team {
width: 400px;
float: left;
}
.team-content {
position: absolute;
right: 5px;
top: 5px;
}
.team-content img {
display: none;
border: 1px dotted red;
width: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="team" class="about-team">
<div class="team-header">
<h2 class="team-text">Our Team</h2>
<div class="divider"></div>
</div>
<div class="section-content">
<div class="row text-center">
<div class="col-xs-6 col-md-3 col-lg-3 member1">
<h2 class="t-seperator">John Doe</h2>
<span>/CEO</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member2">
<h2 class="t-seperator">Jesica Ice</h2>
<span>/DESIGNER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member4">
<h2 class="t-seperator">Anna Moon</h2>
<span>/MARKETER</span>
</div>
<div class="col-xs-6 col-md-3 col-lg-3 member3">
<h2 class="t-seperator">Michael Huge</h2>
<span>/DEVELOPER</span>
</div>
</div>
</div>
</div>
<div id="main-team" class="team-content">
<img src="assets/img/team/team1.jpeg" alt="Team 1">
<img src="assets/img/team/team2.jpg" alt="Team 2">
<img src="assets/img/team/team3.jpg" alt="Team 3">
<img src="assets/img/team/team4.jpg" alt="Team 4">
</div>
So a few changes made: first, I'd left the initial selector wrong. Then, I added some CSS styles so we could see something happening. The advantage of this approach (while it may be longer) is that it's extensible. If you add thirty more employees, you'd have to create a variable for each one, and use that each time. By this approach, it's happening automatically.
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
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);