Bootstrap Table filter by string partial - javascript

I'm using the Bootstrap-table plugin (http://bootstraptable.wenzhixin.net.cn/documentation/) and I'm trying to filter by tags by utilizing the method filterby but can't figure out how to factor in multiple tags that has to come in as a string, separated by commas.
I created an example to illustrate what I'm attempting to achieve. For simplicity,
Here's the html:
<table id="table">
<thead>
<tr>
<th data-field="date">Date</th>
<th data-field="desc">Description</th>
<th data-field="tags">Tags</th>
</tr>
</thead>
</table>
<br>
<button id="filter-general">General</button>
<button id="filter-rotation">Rotation</button>
<button id="clear">clear</button>
Javascript:
var data = [{
"date": "2016-05-10",
"tags": "General, Research, Rotation",
"desc": "Nunc velit lectus, ornare vitae fringilla eget, vestibulum quis tortor."
},{
"date": "2016-04-22",
"tags": "General",
"desc": "Nunc velit lectus, ornare vitae fringilla eget, vestibulum quis tortor."
},{
"date": "2016-03-23",
"tags": "Research, Rotation",
"desc": "Nunc velit lectus, ornare vitae fringilla eget, vestibulum quis tortor."
},{
"date": "2015-11-01",
"tags": "Rotation",
"desc": "Nunc velit lectus, ornare vitae fringilla eget, vestibulum quis tortor."
},{
"date": "2016-08-15",
"tags": "General, Rotation",
"desc": "Nunc velit lectus, ornare vitae fringilla eget, vestibulum quis tortor."
}];
$(function() {
$table = $('#table');
$table.bootstrapTable({
data: data
});
$('#clear').click(function() {
$table.bootstrapTable('filterBy', {});
});
$('#filter-general').click(function() {
$table.bootstrapTable('filterBy', {
tags: "General"
});
});
$('#filter-rotation').click(function() {
$table.bootstrapTable('filterBy', {
tags: "Rotation"
});
});
});
http://jsfiddle.net/zqxwr3uL/6/
Edit: Either by filterby method or from one of the filter extensions.

I think you are out of luck using the filterBy fuction. From the source code (https://github.com/wenzhixin/bootstrap-table/blob/develop/src/bootstrap-table.js):
var f = $.isEmptyObject(this.filterColumns) ? null : this.filterColumns;
// Check filter
this.data = f ? $.grep(this.options.data, function (item, i) {
for (var key in f) {
if ($.isArray(f[key]) && $.inArray(item[key], f[key]) === -1 ||
item[key] !== f[key]) {
return false;
}
}
return true;
}) : this.options.data;
where item[key] is your cell value and f[key] is your filter string. $.inArray is looking for the complete text of the cell in your filter strings.

i know, old session but just change check filter part to this:
for (var key in f) {
if (Array.isArray(f[key]) && !f[key].includes(item[key])) {
return false;
}
if(!Array.isArray(f[key]) ){
if(item[key].search(f[key])==-1){
return false
}
}
}

Related

Mongoose partial text search with sorting by revelance

I'm trying to query my mongodb database via mongoose, sorting the most relevant items first.
The following code works, but only returns results that contain the search parameter as a full word.
E.g. example will return items that include fields such as, ⁣ but{name: "example-item", description: "this is an example description"} but examp won't return that same item. I'd also like for it to search across multiple fields, as my current code does.
I'm aware you can do this partial search using regex but then you're not able to sort by textScore. Is there any way to do both? Sorting after each request is not possible as it will be paginated and handling somewhat large data.
let searchValue = "examp";
let matchingItems = await Items.find(
{
$text: {
$search: searchValue,
}
},
{
score: {
$meta: "textScore"
}
},
{
sort: {
score: {
$meta: "textScore"
}
}
}
);
Example DB data:
[
{name: "dignissim", description: "Lorem ipsum dolor sit amet, consectetur adipiscing elit."},
{name: "Fusce eget.", description: "Nullam malesuada ex sit amet diam ultrices"},
{name: "Duis nec", description: "Proin at dolor at est porta aliquet. Proin viverra imperdiet orci, a ornare tortor"},
{name: "Mauris.", description: "Aenean tristique ante et eros porttitor, ut sodales ipsum pulvinar."},
{name: "Pellentesque", description: "Nam dignissim ipsum a elit fermentum"},
{name: "facilisis augue", description: "Etiam sit amet dolor sed sapien rutrum sodales."},
{name: "erat suscipit", description: "this is an example description"},
]
My schema is defined as below:
const mongoose = require("mongoose");
const schema = new mongoose.Schema({
name: String,
description: String
});
schema.index({ name: "text", description: "text" });
const Items = mongoose.model("Item", schema);

filter data on multiple fields

I am trying to build a filter for JSON object at the moment, the json object looks like this,
created_at: null
deleted_at: null
id: 3
listings: Array(3)
0: {id: 3, name: "Learn the basics of the guitar from the anatomy of the guitar to scales, chords", slug: "learn-the-basics-of-the-guitar-from-the-anatomy-of-the-guitar-to-scales-chords", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "undefined", …}
1: {id: 8, name: "Advanced guitar skills with William Topa", slug: "advanced-guitar-skills-with-william-topa", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "Lorem ipsum dolor sit amet, consectetur adipiscing… laboris nisi ut aliquip ex ea commodo consequat.", …}
2: {id: 9, name: "Music production simplified", slug: "music-production-simplified", description: "We live in a unique and wonderful time where elect… going to give you a lifetime of awesome rockin’.", booking_details: "Lorem ipsum dolor sit amet, consectetur adipiscing… laboris nisi ut aliquip ex ea commodo consequat.", …}
length: 3
__proto__: Array(0)
tag: "Music"
updated_at: null
weight: null
This is part of a bigger object, the hierarchy looks like
[{ data, listings }, {data, listings}]
What I am wanting to do, is filter through the listings array and hide any listings that don't have a cost of "0.00"
Here is what i am trying,
<input type="checkbox" v-model="priceFilter" value="0.00" />
data() {
return {
this.priceFilter: []
}
},
computed: {
filteredTags() {
return this.tags.filter(tag => {
tag.listings.filter(listing => "0.00" === listing.cost);
//console.log(this.checkedPrice, listing.cost);
});
},
},
In the above I just trying to return the listings where the cost matches 0.00 with trigger it via the checkbox being checked but even that does not filter as I wish I still see all listings.
Anyone care to offer any advice?

How can I get the same object in the visitor area as I get in the admin area without the user $uid

Currently on a blog website like I got a problem I didn't expect when I start building it...
I build it like this:
• A admin area where you have to login where you can write/delete articles.
• A public area where you don't need to login where you can see the articles write in the admin area.
My database is build like below as you can see every user got a $uid. So because of how it's build my service look like this:
{
"articles" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORxrYnctixsx5sQ5DM" : {
"author" : "Zinedine Zidane",
"categories" : [ "Football", "Tennis" ],
"content" : "<p>Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.Constituendi autem sunt qui sint in amicitia fines et quasi termini diligendi. De quibus tres video sententias ferri, quarum nullam probo, unam, ut eodem modo erga amicum adfecti simus, quo erga nosmet ipsos, alteram, ut nostra in amicos benevolentia illorum erga nos benevolentiae pariter aequaliterque respondeat, tertiam, ut, quanti quisque se ipse facit, tanti fiat ab amicis.</p>",
"date" : 1539158014424,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41666967_311898482736538_5532086598150712503_n.jpg?alt=media&token=6b13fe37-357e-45db-8d0e-4436e166d359",
"name" : "Thalassio otium quem et hortaretur. \t"
},
"-LORy85GKdT9U9p_Iolk" : {
"author" : "David Kidouille",
"categories" : [ "Football", "ChatMignon" ],
"content" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
"date" : 1539158086263,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/36981961_1869531810009121_4498273348232413184_n.jpg?alt=media&token=47fc2e67-d198-4533-8939-abc5d3dbed51",
"name" : "Omni habere atque perpetuae sic."
},
"-LOTQNaI7ry3WRavCjNt" : {
"author" : "Sophia Green",
"categories" : [ "Espresso", "Title" ],
"content" : "<p>Harum trium sententiarum nulli prorsus assentior. Nec enim illa prima vera est, ut, quem ad modum in se quisque sit, sic in amicum sit animatus. Quam multa enim, quae nostra causa numquam faceremus, facimus causa amicorum! precari ab indigno, supplicare, tum acerbius in aliquem invehi insectarique vehementius, quae in nostris rebus non satis honeste, in amicorum fiunt honestissime; multaeque res sunt in quibus de suis commodis viri boni multa detrahunt detrahique patiuntur, ut iis amici potius quam ipsi fruantur.</p><p>Ibi victu recreati et quiete, postquam abierat timor, vicos opulentos adorti equestrium adventu cohortium, quae casu propinquabant, nec resistere planitie porrecta conati digressi sunt retroque concedentes omne iuventutis robur relictum in sedibus acciverunt.</p><p>Non ergo erunt homines deliciis diffluentes audiendi, si quando de amicitia, quam nec usu nec ratione habent cognitam, disputabunt. Nam quis est, pro deorum fidem atque hominum! qui velit, ut neque diligat quemquam nec ipse ab ullo diligatur, circumfluere omnibus copiis atque in omnium rerum abundantia vivere? Haec enim est tyrannorum vita nimirum, in qua nulla fides, nulla caritas, nulla stabilis benevolentiae potest esse fiducia, omnia semper suspecta atque sollicita, nullus locus amicitiae.</p>",
"date" : 1539182528987,
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/37112713_499156913858390_6321776699583234048_n.jpg?alt=media&token=dea02d84-dcc8-427e-92d1-92529499e052",
"name" : "Plerisque honoribus inventu in verae descendant quas in graves enim"
}
}
},
"contact" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"adress" : "Bla Bla Bla",
"email" : "michel#gmail.com",
"facebook" : "www.facebook.com",
"phone" : "0606060606"
}
},
"evenements" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORx0d49L5W1OHbaPkz" : {
"content" : "<p>Eodem tempore Serenianus ex duce, cuius ignavia populatam in Phoenice Celsen ante rettulimus, pulsatae maiestatis imperii reus iure postulatus ac lege, incertum qua potuit suffragatione absolvi, aperte convictus familiarem suum cum pileo, quo caput operiebat, incantato vetitis artibus ad templum misisse fatidicum, quaeritatum expresse an ei firmum portenderetur imperium, ut cupiebat, et cunctum.</p>",
"dateEnd" : "20/08/1995",
"dateStart" : "17/08/1995",
"name" : "Stand de tir au pigeon",
"place" : "33 rue de la Liberté, Bourgoin Jallieu"
}
}
},
"medias" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORymdySlsQ82_rZ6kk" : {
"description" : "Bla Bla Bla Bla",
"titre" : "30 ans de michel",
"type" : "image",
"url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41466540_333985383837957_6494746608337518152_n.jpg?alt=media&token=079311d7-c42e-4e21-933e-36573e88a893"
},
"-LORyzf8ft5hS_MV_B10" : {
"description" : "klsjbvsjdkbvjkshd",
"titre" : "Bla Bla bla",
"type" : "image",
"url" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/41532985_724838064517122_5880047170186967403_n.jpg?alt=media&token=86632def-47b3-4b30-84c9-c9af571da17d"
}
}
},
"sports" : {
"xgbKhFzeY1XvIlluGItaBPAvwQQ2" : {
"-LORzZ2xq_JszbFaFyyn" : {
"description" : "<p>Nec vox accusatoris ulla licet subditicii in his malorum quaerebatur acervis ut saltem specie tenus crimina praescriptis legum committerentur, quod aliquotiens fecere principes saevi: sed quicquid Caesaris implacabilitati sedisset, id velut fas iusque perpensum confestim urgebatur impleri.</p>",
"handisport" : "<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>",
"image" : "https://firebasestorage.googleapis.com/v0/b/csbj-handisport-38.appspot.com/o/42004027_2218122771593693_1511293494740179714_n.jpg?alt=media&token=430ddee9-a818-44ac-b80c-2483be38f1c0",
"name" : "Football",
"nbrPlayer" : 10,
"partTime" : 30
}
}
}
}
My Service in the Admin Area where I can access the $uid
import { Injectable } from '#angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs/observable/of';
import { AngularFireDatabase } from 'angularfire2/database';
import { Store } from '../../store';
import { AuthService } from './auth.service';
export interface Article {
name: string,
author: string,
categories: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
#Injectable()
export class ArticlesService {
articles$ = this.db.list<Article>(`articles/${this.uid}`).snapshotChanges()
.pipe(map(actions =>
actions.map(a => ({ key: a.key, ...a.payload.val() }))
))
.pipe(tap(next => {
this.store.set('articles', next);
})
);
constructor(
private store: Store,
private db: AngularFireDatabase,
private authService: AuthService
) {}
get uid() {
return this.authService.user.uid;
}
getArticle(key: string) {
if (!key) return of({});
return this.store.select<Article[]>(`articles`)
.pipe(filter(Boolean))
.pipe(map(articles => articles.find((article: Article) => article.key === key)));
}
addArticle(article: Article) {
return this.db.list(`articles/${this.uid}`).push(article);
}
updateArticle(key: string, article: Article) {
return this.db.object(`articles/${this.uid}/${key}`).update(article);
}
removeArticle(key: string) {
return this.db.list(`articles/${this.uid}`).remove(key);
}
}
My Service in the Admin Area where I can't access the $uid
import { Injectable } from '#angular/core';
import { filter, map, tap } from 'rxjs/operators';
import { of } from 'rxjs';
import { AngularFireDatabase } from 'angularfire2/database';
import { Store } from '../../store';
export interface Article {
name: string,
author: string,
category: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
#Injectable()
export class ArticlesService {
articles$ = this.db.list<Article>(`articles`).snapshotChanges()
.pipe(map(userId =>
userId.map(a => ({ ...a.payload.val() }))
)).pipe(tap(next => {
this.store.set('articles', next);
}));
constructor(
private store: Store,
private db: AngularFireDatabase
) {}
getArticle(key: string) {
if (!key) return of({});
return this.store.select<Article[]>(`articles`)
.pipe(filter(Boolean))
.pipe(map(articles => articles.find((article: Article) => article.key === key)));
}
}
So When I call the service for get my articles in the admin area I get and in the public area I get.
I find a way to get the value but with this way I lose the key object.
export interface Article {
name: string,
author: string,
category: string[],
content: string,
date: string,
image: string,
key: string,
$exists: () => boolean
}
How can I get the same object in the visitor area as I get in the admin area ?

TypeError: Cannot read property 'id' of undefined (REACTJS)

Am still new to Reactjs, thought have tried all I can, but still can't get through this error "TypeError: Cannot read property 'id' of undefined"
please someone help below is my code.
if(this.props.controller === 'location'){
eventData = Object.keys(this.props.heda).map( evKey => {
return Object.keys(evKey).map( post => {
return [...Array(this.props.heda[evKey][post])].map( lol => {
return <Event key= {lol['id']}
descriptions = {lol['description']}
headings = {lol['title']}
id = {lol['id']}
clicked = { ()=> this.viewSelectedEvent(lol['id']) }/>;
}) ;
});
});
}
Error full stacktrace:
here is my data from flask that am trying to loop.Am trying to convert each object into an array, then loop through the array. I also tried to console.log(lol) and i get the data as in the image below
events = [
{
'id': 1,
'title': u'HHGHHMjshjskksjks',
'description': u'Cras justo odio dapibus ac facilisis in egestas eget qua ',
'location':'jkknxjnj',
'category':'party',
'rsvp': False,
'event_owner':1
},
{
'id': 2,
'title': u'khjhjshjsjhdndjdh',
'description': u'jhhnbsbnsbj',
'location':'jhjhsjhjhsjhjdhsd',
'category':'party',
'rsvp': False,
'event_owner':2
},
{
'id': 3,
'title': u'jhjshjsdhjshdjshjsd',
'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec elit non mi porta gravida at eget metus.',
'location':'kjkshjhjhjbsnbsd',
'category':'party',
'rsvp': False,
'event_owner':2
},
{
'id': 4,
'title': u'jjhjshjhsjhjshjjhjhd',
'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec elit non mi porta gravida at eget metus.',
'location':'kjisisiisdsds',
'category':'party',
'rsvp': False,
'event_owner':2
},
{
'id': 5,
'title': u'uiujsdshuuihuyksjhjs',
'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec elit non mi porta gravida at eget metus.',
'location':'sjnsisuis',
'category':'party',
'rsvp': False,
'event_owner':2
},
{
'id': 6,
'title': u'iusijksuiksuhj suyuys jhu ',
'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec elit non mi porta gravida at eget metus.',
'location':'isuisiiws',
'category':'party',
'rsvp': False,
'event_owner':2
},
{
'id': 7,
'title': u'jujusi jsuoios jshuysd',
'description': u'Cras justo odio, dapibus ac facilisis in, egestas eget quam. Donec elit non mi porta gravida at eget metus.',
'location':'area h',
'category':'party',
'rsvp': False,
'event_owner':2
},
]
With [...Array(this.props.heda[evKey][post])] you create an array which has as the first element the array this.props.heda[evKey][post]).
Maybe you wanted to say [...this.props.heda[evKey][post]] to create a clone of the array?
Because he is not able to find id in this.props.heda[evKey][post] object. So firstly you should console your this.props.heda[evKey][post] object after that I think you will get your actual problem.
Please try below snippet:
this.props.heda.map((evVal, evKey) => {
return evVal.map((postVal, postKey) => {
...
}
}
Now this.props.heda[evKey][postKey] will give you the expected object.

Angular repeating images

New to angular and developing a simple page just to learn the inner workings. What I have is a div that display name price and description along with a button and a full image. What I'm trying to do is underneath that full image display 2-3 additional images. The problem is the same full image is displaying again and none of the additional images are displaying.
Here is the angular
(function () {
var app = angular.module('gemStore', []);
app.controller('StoreController', function () {
this.products = gems;
});
var gems = [
{
name: 'Defmei',
price: 2.95,
description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ',
canPurchase: true,
soldOut: false,
images: [
{
image: "Images/image1.jpg",
image: "Images/image2.jpg",
image: "Images/image3.jpg"
}
]
},
{
name: 'Sijoi',
price: 5.95,
description: 'Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. ',
canPurchase: true,
soldOut: true,
images: [
{
image: "Images/image4.jpg",
image: "Images/image3.jpg",
image: "Images/image2.jpg"
}
]
}
]
})();
Here is the HTML
<body data-ng-controller="StoreController as store" >
<div class="display" data-ng-repeat="product in store.products">
<h1>{{product.name}}</h1>
<h2>{{product.price | currency}}</h2>
<p> {{product.description}} </p>
<img class="imageStyles" data-ng-src="{{product.images[0].image}}"/>
<br />
<div data-ng-repeat="image in product.images">
<img data-ng-src="{{image.image}}" class="thumbs" />
</div>
<button data-ng-show="product.canPurchase">Add to cart</button>
</div>
</body>
That image object seems "broken", you're practically redefining the image attribute 3 times.
In javascript, objects have a syntax like { attribName1: attValue1, attribName2: attValue2 ...}
What you're creating here:
images: [
{
image: "Images/image1.jpg",
image: "Images/image2.jpg",
image: "Images/image3.jpg"
}
]
Is an array with 1 item, which is an object, with 1 property, "image", with a value of... "Images/image3.jpg" maybe (or whatever, I wouldn't be surprised if double-defining attributes like this was in fact undefined behaviour).
What you probably want instead is either an array with 3 elements, or an object with 3 distinct attributes, ie:
images: [
{
"image1": "Images/image1.jpg",
"image2": "Images/image2.jpg",
"image3": "Images/image3.jpg"
}
]
You can iterate through array members and object attributes too with ng-repeat, but you have to change your code accordingly.
Your images array only has one item in it with image defined three times. Change it like the following so that there are three separate items and it should work.
images: [
{image: "Images/image4.jpg"},
{image: "Images/image3.jpg"},
{image: "Images/image2.jpg"}
]

Categories