Filtering spcific with checkboxes - checkbox

My question is that I want a filtering system that will filter by checked checkboxes.
The tool is to my comparison website where I compare TV packages.
my visitors should filter the packages by the tv-channels they want to se.
example;
Checkbox 1: Discovery
Checkbox 2: Animal PLanet
Checkbox 3: Disney Channel
Output should be the matching TV-package
Package 1: (contains Discovery and Disney channel)
Package 2: (contains Animal Planet, Disney channel)
Package 3: (contains Animal Planet)
So if checkbox 1 is checked it should only show package 1.
if checkbox 1 + checkbox 2 is checked it should say "No match found, but this package was was closest to your choice"
if checkbox 2 + checkbox 3 is checked it should only show package 2 which match the visitors choice exactly.
I hope your can help me out. I have been searching a lot after this specific solution without any success.

I think it should be in Jquery. i have seen some simular filtering examples, but no one there are like my wish above.

This is an old question, but... I'll take a shot. Working jsfiddle: http://jsfiddle.net/a0nnrfua/
I think a lot really depends on how you intend to define "closest", but presuming a jQuery solution and hopefully your browser requirements aren't TOO far in the past, you could use the data- attributes and jQuery to come up with some relatively simple functions. Or even use the value portions of the checkboxes really.
Psuedocode, it would look like:
Define a click or change handler to detect whenever a checkbox has been touched/changed.
Define a function that will scan all checked items and pass the values into your "closest package" function.
Based on the results of that function, filter your package selection so that your choices are highlighted or marked in some way.
So let's presume the following HTML markup:
<h3>TV Channels</h3>
<div id="TVChannelSelections">
<input type="checkbox" class="tvchannel" name="tvchannel" id="tvchannel_Discovery" value="Discovery" />
<label for="tvchannel_Discovery">Discovery Channel</label>
<br/>
<input type="checkbox" class="tvchannel" name="tvchannel" id="tvchannel_AnimalPlanet" value="Animal Planet" />
<label for="tvchannel_AnimalPlanet">Animal Planet</label>
<br/>
<input type="checkbox" class="tvchannel" name="tvchannel" id="tvchannel_DisneyChannel" value="Disney Channel" />
<label for="tvchannel_Disney">Disney Channel</label>
<br/>
</div>
<div id="message"></div>
<h3>Packages</h3>
<div id="FilteredPackages">
<div class="package deselected" id="Package1" data-channels="Discovery,Disney Channel">Package #1</div>
<div class="package deselected" id="Package2" data-channels="Animal Planet,Disney Channel">Package #2</div>
<div class="package deselected" id="Package3" data-channels="Animal Planet">Package #3</div>
</div>
So in jQuery, your generic change or click handler would be defined in code: Note that I'm saying, any element on your page that has the class "tvchannel" defined, if there's ever a change that occurs, run my filter function.
<script type="text/javascript" src="../path/to/jQuery/library"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".tvchannel").on("change", function() {
FilterMySelectedChannels();
});
});
</script>
Now we can define your Filter function. We're going to assume two things. #1, that we want to find all the selected checkboxes and their values. Then we're going to iterate through the data-channels property of all of our packages (defined as elements with class = "package"). We'll use some form of string comparison and boolean logic to define what a complete match is vs. a close but no cigar match vs. a complete fail.
In order to keep track of things I'm using 3 classes, selected, deselected, and close.
In css, you can decide whether you want notselected to mean "hide the package completely" (i.e. display: none;) or maybe you want it to be visible but greyed out and "struck out" (i.e. text-decoration: strikethrough; color: grey;}
I'm going to use kind of a brute force way of doing the comparison. There are better array functions and comparison functions in javascript, but this should be relatively clear for most people and I trust the good folks at stackoverflow to chime in with better solutions. But this should get you started. :)
<script type="text/javascript">
function FilterMySelectedChannels() {
$checkedboxes = $(".tvchannel:checked");
$packages = $(".package");
var bAnyFound = false;
$packages.each(function () {
var bCloseButNoCigar = false;
var bCompleteMatch = true;
var packagearray = $(this).data("channels").split(",");
var $currentPackage = $(this);
$checkedboxes.each(function () {
if ($.inArray($(this).val(), packagearray) != -1) {
bCloseButNoCigar = true;
} else {
bCompleteMatch = false;
}
});
if (bCompleteMatch) {
$currentPackage.removeClass("selected").removeClass("deselected").removeClass("close").addClass("selected");
bAnyFound = true;
} else if (bCloseButNoCigar) {
$currentPackage.removeClass("selected").removeClass("deselected").removeClass("close").addClass("close");
} else {
$currentPackage.removeClass("selected").removeClass("deselected").removeClass("close").addClass("deselected");
}
});
if (bAnyFound) {
$("#message").html("The following matches were found");
} else {
$("#message").html("No actual matches were found, but here are some close matches based on your selections");
$(".package.close").removeClass("deselected").removeClass("close").removeClass("selected").addClass("selected");
}
}
</script>
<style type="text/css">
.selected {
color: red;
background-color: yellow !important;
}
.deselected {
color: grey;
text-decoration: strike-through !important;
background-color: white !important;
}
</style>
There are obvious optimizations that could probably work here, but it's a start for those trying to do something similar. Note that it assumes that your markup is dynamically generated or properly coded. If you need to guard against human typos, converting your text using .toLowerCase/UpperCase and using the .Trim functions to eliminate extra space will assist. But you still have to choose your data values wisely so there's no overlap. And if you choose them well enough you can use better techniques such as regular expressions and wildcard searches to make the code a bit shorter.
Hope this helps someone!

Related

How to add attributes to elements with HtmlPurifier?

I'm looking to purify HTML with the HtmlPurifier package and add attributes to certain elements. Specifically, I'd like to add classes to <div> and <p> elements so that this:
<div>
<p>
Hello
</p>
</div>
Gets purified/transformed into this:
<div class="div-class">
<p class="p-class">
Hello
</p>
</div>
How would one go about doing this with HtmlPurifier? Is it possible?
I believe you could do this by doing something along these lines (though please treat this as pseudocode, the last time this scenario worked for me was years ago):
class HTMLPurifier_AttrTransform_DivClass extends HTMLPurifier_AttrTransform
{
public function transform($attr, $config, $context) {
$attr['class'] = 'div-class';
return $attr;
}
}
class HTMLPurifier_AttrTransform_ParaClass extends HTMLPurifier_AttrTransform
{
public function transform($attr, $config, $context) {
$attr['class'] = 'p-class';
return $attr;
}
}
$htmlDef = $this->configuration->getHTMLDefinition(true);
$div = $htmlDef->addBlankElement('div');
$div->attr_transform_post[] = new HTMLPurifier_AttrTransform_DivClass();
$para = $htmlDef->addBlankElement('p');
$para->attr_transform_post[] = new HTMLPurifier_AttrTransform_ParaClass();
Remember to allowlist the class attribute for div and p as well, if you haven't already.
That said, at first glance, HTML Purifier doesn't seem to be the right place for this kind of logic, since adding class names isn't relevant for the security of your site (or is it?). If you're already using HTML Purifier to allowlist your HTML tags, attributes and values, and just want to leverage its HTML-parsing capabilities for some light-weight additional DOM manipulation, I see no particular reason not to. :) But it might be worth reflecting on whether you want to add the classes using some other process (e.g. in the frontend, if that's relevant for your use case).

Cypress: cannot find elements in calendar popup

I cannot interact with the date picker (popup) in my Cypress tests.
I tried .find() and .get() on every div class but each time it says
Timed out retrying after 4000ms: Expected to find element: .cdk-overlay-container, but never found it
This is my test code:
cy.get('#signup-step-pers-details').within(() => {
cy.get('[name="firstName"]').type(user.firstName)
.get('[name="surname"]').type(user.lastName)
.get('#select-gender').click()
.get('.ng-dropdown-panel-items').contains(user.gender, {matchCase: false}).click()
.get('#input-dateOfBirth').click()
.find('.owl-dt-popup').click()
.get('.owl-calendar-year').contains(2002).click()
I tried adding some wait time but that didn't help either.
#KKhan is correct, the Angular Date Time Picker opens in a cdk-overlay-container at the foot of the document.
More detail on the layout:
<body>
...
<div id="signup-step-pers-details>
...
<div id="input-dateOfBirth"></div>
</div>
...
<div class="cdk-overlay-container">
<owl-date-time-container>
...
</owl-date-time-container>
</div>
</body>
Using cy.get('#signup-step-pers-details').within(() => { restricts commands inside to that section of the DOM, but the owl-date-time-container is outside of that.
You can use this approach Cypress how to temporarily escape from a cy.within()
cy.get('#signup-step-pers-details').within(() => {
// cy.root() === #signup-step-pers-details
cy.get('[name="firstName"]').type(user.firstName)
.get('[name="surname"]').type(user.lastName)
.get('#select-gender').click()
.get('.ng-dropdown-panel-items').contains(user.gender, {matchCase: false}).click()
.get('#input-dateOfBirth').click()
// shift cy.root() to date-time-picker
cy.document().its('body').find('owl-date-time-container').within(() => {
cy.get('button.owl-dt-control-period-button').click()
cy.contains('2002').click()
cy.contains('Aug').click()
cy.contains('23').click()
})
// back to cy.root() === #signup-step-pers-details
cy.get('#select-nationality').click()
})
Note I've used .owl-dt-control-period-button which is correct for the current version of Angular Date Time Picker, but perhaps you have an older version that requires .owl-calendar-year.
This sequence
.get('#input-dateOfBirth').click()
.find('.owl-dt-popup').click()
is expecting to find the date popup within the dateOfBirth control.
You may simply need
.get('#input-dateOfBirth').click()
.get('.owl-dt-popup').click()
Generally you see cy.get() for each item, not chaining all the gets as you have done. That still works because .get() always starts it's search at cy.root(), which is set to #signup-step-pers-details by the .within().
But the .find() is different, it starts it's search at the previous subject, which is the DOB control.
I should add, in case you were expecting the date popup to actually be inside the DOB input, that cdk-overlay-container is added when the popup is made visible, at the bottom of the <body></body> tag (take a look in devtools).
<div class="cdk-overlay-container">...</div>
</body>
Your approach of using contains is good but there is another syntax you may use for the purpose of selecting a date:
cy.get('#signup-step-pers-details').within(() => {
cy.get('[name="firstName"]').type(user.firstName)
.get('[name="surname"]').type(user.lastName)
.get('#select-gender').click()
.get('.ng-dropdown-panel-items').contains(user.gender, {matchCase: false}).click()
.get('#input-dateOfBirth').click()
.find('.owl-dt-popup').click()
.contains('.owl-calendar-year', '2002').click()

PrimeNG select datatable cell

I am working on a project using Angular 4 and PrimeNG where I need to be able to double click on a cell, selected it and open a dialog to do some modifications on the cell's underlying data.
As far as I can see from the documentation, currently there is no way to accomplish this. What is the best way to handle this situation?
Thanks.
So after some playing around I came up with a solution, which being far from perfect serves the purpose while we wait for the folks from PrimeNG (which I love, btw) to include this functionality.
The first issue was to determine which cell the user double-clicked on. I did that by having all column's templates in a div which I can get a reference to:
<p-dataTable #grd [value]="view"
(onRowDblclick)="editTemplate($event)"
(onRowClick)="clearSelection($event)">
<p-column field="SomeFieldName" header="Header" [editable]="false">
<ng-template let-col let-data="rowData" pTemplate="body">
<div [id]="col.field" class="cell-content">
<div [innerHTML]="data[col.field]" class="center-parent-screen"></div>
</div>
</ng-template>
</p-column>
All columns I am interested in handling on double click are wrapped in the div with class cell-content. Also notice the id attribute. It is set to match the field. Then in the onRowDblclick event:
editTemplate(e: any) {
let target = e.originalEvent.toElement.closest('div.cell-content');
if (target && target.id) {
let td = target.closest('td');
if (td) {
td.style.backgroundColor = 'darkorange';
td.style.color = 'white';
}
let fieldValue = e.data[target.id];
//do something with this data
}
}
The key here is the id attribute. Once we have that now we know which cell was clicked and we can proceed to do what we need to do. Also notice that I get a reference of the parent TD element and set the background and the color of the cell. Once you are finished working with it, you can clear the formatting to go back to normal.
You can also use the onRowClick event to clear the selection like so:
clearSelection(e: any) {
let target = e.originalEvent.toElement.closest('div.cell-content');
if (target && target.id) {
let td = target.closest('td');
if (td) {
td.style.backgroundColor = 'white';
td.style.color = 'black';
}
}
}
I know manipulating the DOM directly is not the way to go, but until we get the new version of PrimeNG that includes this functionality, this will do, at least for me.
Please let me know if you have a better way of doing this.

Ask to confirm when changing tabs in angular bootstrap

I have tabs with forms and I want ask the user to confirm or discard their changes when changing tabs. My current code works
<uib-tab heading="..." index="3" deselect="main.onDeselect($event)" ... >
this.onDeselect = function($event) {
if(...isDirty...) {
if($window.confirm("Do you want to discard?")) {
... discard (and go to new tab) ...
} else {
$event.preventDefault(); //stays on current tab
}
}
}
The problem is I want to change confirm to javascript dialog and I will get result in callback.
I planed to preventDefault() all and then switch manually, but I cannot figure out where to get new tab id.
Any solution is appreciated. Even if it is easier in other tab implementations.
I use AngularJS v1.4.7, ui-bootstrap-tpls-1.3.3.min.js
You can make use of $selectedIndex and the active property for that purpose. See this Plunk
One thing to be noted here is that when we manually change the active property, it again fires the deselect event which needed to be handled. Otherwise it seems to do what you wanted.
Edit
Indeed as noted in the comments, the deselect carries the HTML index rather than what is passed in in the tab index property. A workaround could be in this: Another Plunk. Here I'm pulling the actual index from the HTML index.
And a little research indicates that this issue might as well be fixed already with 3.0 bootstrap tpl See this.
I spent some time with different approaches and this one is stable for some time. What I do is to prevent deselect at the beginning and set the new tab in callback if confirmed to loose changes...
this.onDeselect = function($event, $selectedIndex) {
var me = this;
if(this.tabs.eventDirty || this.tabs.locationDirty || this.tabs.contractDirty) {
$event.preventDefault();
var alert = $mdDialog.confirm({
title: 'Upozornění',
textContent: 'Na záložce jsou neuložené změny. Přejete si tyto změny zrušit a přejít na novou záložku?',
ok: 'Přijít o změny',
cancel: 'Zůstat na záložce'
});
$mdDialog
.show( alert )
.then(function() {
$rootScope.$emit("discardChanges");
me.tabs.activeTab = $selectedIndex;
})
}
};

How to use gridfilters Plugin AND programmatically clear/set the filters?

In my app (ExtJS 5.0.1) I'm trying to use a grid with the gridfilters Plugin AND shortcut buttons (and also from a tree) with custom/hardcoded fiters.
I was able to partially mimic the set and clear of the filters, but I'm having the following problems:
1- When I set a filter via grid.filters.store.addFilter(..) the style of the column title doesn't change to bold, and the grid filter checkbox stays unchecked.
2- Same as 1 but reversed... first I set the filter on the column, when I clear the filter the column stays bold, but in this case the checkbox is cleared (as it should).
3- When I'm using summary feature 'sometimes' the total is not updated
So, my question is:
Is there a proper way to programmatically set/clear filters mimicking the gridfilter Plugin ?
I've put a minimal Fiddle to simulate this.
https://fiddle.sencha.com/#fiddle/akh
Best Regards,
Ricardo Seixas
Just use filter instance on column:
var column = grid.columnManager.getColumns()[0];
column.filter.setValue('J');
column.filter.enable();
Working sample: http://jsfiddle.net/3be0s3d8/7/
For List Filters use the following override to enable the setValue method:
//Enable setting filter values in list filters
Ext.define('Ext.ux.fixed.ListFilter', {
override: 'Ext.grid.filters.filter.List',
setValue: function(values) {
var me = this, len = values.length;
if(!values) {
me.callParent();
return;
}
if(!me.menu){
me.createMenu();
}
me.filter.setValue(values);
if (len && me.active) {
me.updateStoreFilter(me.filter);
} else {
me.setActive(!!len);
}
}
});
You can directly change the styles in the GridFilter.css file :
<link rel="stylesheet" type="text/css" href="js/lib/ext-4.2.1.883/ux/grid/css/GridFilters.css" />
By changing this element :
.ux-filtered-column {
font-style: italic;
font-weight: bold;
background: #56b8ff;
}
Hope this helps.
In the latest release (5.1) Ext's ChainedStore worked well for me.

Resources