Isotope Search Filter almost figured out - javascript

Need some help with the last bit of it...
I have a fiddle here...
I have the filtered searches by button click, and the search by keyword. They work independently, but I can't seem to get them to work together.
I think the function lies somewhere in here, but I'm a bit lost...
function isotopeSearch(kwd)
{
// reset results arrays
var matches = [];
var misses = [];
$('.item').removeClass('match miss'); // get rid of any existing classes
$('#noMatches').hide(); // ensure this is always hidden when we start a new query
if ( (kwd != '') && (kwd.length >= 2) ) { // min 2 chars to execute query:
// loop through brands array
_.each(items, function(item){
if ( item.first.indexOf(kwd) !== -1 ) { // keyword matches element
matches.push( $('#'+item.id)[0] );
} else {
misses.push( $('#'+item.id)[0] );
}
});
// add appropriate classes and call isotope.filter
$(matches).addClass('match');
$(misses).addClass('miss');
$container.isotope({ filter: $(matches) }); // isotope.filter will take a jQuery object instead of a class first as an argument - sweet!
if (matches.length == 0) {
$('#noMatches').show(); // deal with empty results set
}
} else {
// show all if keyword less than 2 chars
$container.isotope({ filter: '.item' });
}
}
EDIT: I'm trying to make it searchable only by first/last name.

It basically looks like your "*" selectors are causing the problem on a couple of All buttons. If you simply make them blanks "" it seems to work.
I put this alert in your code and noticed the selectors got a little weird after a few selections:
var selector = isoFilters.join('');
alert(selector);
You wound up with selectors like **.ar
JSFiddle here: http://jsfiddle.net/TrueBlueAussie/2pasq/14/
There is not a full set of item values to test all combinations, but it seems to work if you drop the two "*" filters.

Related

using javascript with a string that contains

Hi I am currently using java to hide certain tabs and fields on my forms depending on the population of dropdowns, for example here is a code that is working:
//Display Transfer tab if it is a transfer application
var ctrlApplicationType = Runner.getControl(pageid, 'ApplicationType');
ctrlApplicationType.on('change', function(e)
{
if (this.getValue() == 2)
{
var tabs = pageObj.getTabs(); tabs.show(2);
}
else
{
var tabs = pageObj.getTabs(); tabs.hide(2);
}
}
);
In the example above the dropdown is fed from a lookup table and returns the primary key INT, hence ==2 works fine.
However I now have a problem when I am trying to get this to work with a checkbox, because the problem is a checkbox can have multiple options.
My lookup table for checkbox has 5 options, so if i ticked option 1, 2 and 3, the field (string) is stored as 1,2,3.
What I need to do is to do change the above code so it returns true if it contains 1, ie
if (1,2,3) contains 1 then true
if (2,3) contains 1 then false.
Any ideas would be much appreciated
Okay, against my better judgement (I'd really like to see you make your own attempt based on the information I've already given you), here you go...
var selectedString = "1,2,3"; // from your code, this is this.getValue()
var selectedArray = selectedString.split(","); // split the string into an array using a comma (,) as the split point
var foundInArray = selectedArray.includes('1'); // foundInArray is now a boolean indicating whether or not the value '1' is one of the values in the array.
if(foundInArray)
{
// do the found action
}
else
{
// do the not found action
}
If you want to compare against integer values instead of string values, that's easy enough too.
var integerArray = selectedArray.map(function(x){ return parseInt(x); });
var foundInArray = integerArray.includes(1);
Finally, all of this can be chained into a one-liner:
if(selectedString.split(",").map(function(x){return parseInt(x);}).includes(1))
{
// do found action
}
else
{
// do not found action
}
To iterate through a fixed list and show/hide each, you can do this...
var possibleTabs = [1,2,3,4,5];
for(n in possibleTabs)
{
if(selectedString.split(",").map(function(x){return parseInt(x);}).includes(n))
{
var tabs = pageObj.getTabs(); tabs.show(n);
}
else
{
var tabs = pageObj.getTabs(); tabs.hide(n);
}
}
This, of course, assumes that there is a relation between the checkbox value and the tabs. If there's not, then you're going to have to list them all out as individual if/elseif/else statements, and that is going to get out of hand really quickly.

How to remove elements from a selector

I'm struggling to get a piece of code to work but I'm not a jquery guy so please bear with me.
I have an outer DIV ($scope). It contains all kinds of inputs.
I find all the entries for each input type and filter them to get the ones with values. These are stored in $entries.
$inputs contains all the inputs regardless of type or status.
What I'm trying to do is remove $entries from $inputs to leave the difference.
It doesn't work, and at the moment I'm not getting any errors firing back, so nothing to go on.
My first thought is that jquery is unable to match the elements in one list with the other as it just holds an index, not the actual object. This could be totally wrong (please refer back to line 1).
Either way, I need to find a way of getting all elements and segegating them into 2 bits - those with values and those without.
All help appreciated.
function inputLoaded(isPostback) {
if (typeof Page_Validators !== "undefined") {
$scope = $(".active-step:first");
$inputs = $scope.find(inputs);
$cb = $scope.find(checkboxes).filter(":checked");
$rb = $scope.find(radios).filter(":checked");
$sb = $scope.find(selects).filter(function () { return $(this).val() !== "None"; });
$ta = $scope.find(textareas).filter(function () { return $(this).val(); });
$tb = $scope.find(textboxes).filter(function () { return $(this).val(); });
$entries = $cb.add($rb).add($sb).add($ta).add($tb);
// Do things with $entries here
// Get elements that have not got entries
$el = $inputs.remove($entries);
}
}
The not() method can take a jQuery object whose contents will be excluded from the jQuery object you apply it to. It looks exactly like what you're looking for:
// Get elements, excluding entries.
$el = $input.not($entries);

Search items in a list, what is good to use?

It is not really a issue, im just wondering I have a list with alot of names and a search function bounded to it. It is all done in jquery and just put every element on display none when it is not matched with the input
It works perfect but I am not really sure this is the 'cleanest' way to do this, cause every element gets updated with a bunch of css styles everytime.
Is it worth to try out angular or some similar solution to achieve it or a complete overkill for such a small task?
Updated:!
My current code:
var value = $input.val(),
$persons = $teamCatagory.find('li');
$persons.hide();
var found = $persons
.filter(function () {
$persons.hide();
return $(this).text()
.match(new RegExp(value, "gi"))
})
.show()
.length > 0;
if(value.length === 0 ) {
$persons.show().removeAttr('style');
}
if (!found) {
$persons.hide();
console.log("found nothing");
}
};

Using Jquery Filter as a way to filter links on a page

I have a list of links on a page and a set of checkboxes that should filter the links so that only the ones that have the specific criteria will be active. My rudimentary attempt to do this involves creating an array of all the filter options that are active and running a .filter(Array) to make those active and a .not(Array) to disable the other links.
The problem is that if more than one filter options is selected any link that matches either filter option will be active. When in reality what i want is only the links that match ALL the filter options to be active.
Here is my stripped down version in jsFiddle
var filterAll = ["filter-F_0", "filter-F_1", "filter-F_2", "filter-F_3", "filter-F_4", "filter-P_0", "filter-P_1", "filter-P_2", "filter-P_3", ]
var filterActive = [];
function filterApps(){
if(filterActive.length == 0)
{
filterReset();
return;
}
var arrActive = $.map(filterActive, function (val) {
return '[' + val + ']'
}).join(",")
addToLog("arr = " + arrActive);
$(".appLink").filter(arrActive).css(activeAppCSS).addClass("active").removeClass("disable");
$(".appLink").not(arrActive).css(disabledAPPCSS).addClass("disable").removeClass("active");}
You have complicated many things here, using attribute's name for filtering the elements is a terrible idea (sorry), you could use data-* attributes that store the filtering criteria in an array. If I have understood the question correctly something like the following should work, this solution reads the attributes' name using attributes property, it should be noted that it's not the most efficient way of doing the task and as Array object's .filter() method is used it doesn't work in older browsers that don't support ES5, for supporting those browsers you can use a shim.
var $links = $('.appLink');
var $checkboxes = $('input[type=checkbox]').on('change', function () {
// Creating an array of values
var checked = $checkboxes.filter(':checked').map(function () {
return this.value.toLowerCase();
}).get();
// Filtering the .appLink elements by reading the attributes
// and comparing the filtered array's length with the checked one
$links.removeClass('matched').filter(function () {
return [].slice.call(this.attributes).filter(function (a) {
return a.name.indexOf('filter') === 0;
}).filter(function(f) {
return $.inArray(f.name.replace('filter-', ''), checked) > -1;
}).length === checked.length;
}).addClass('matched');
});
http://jsfiddle.net/85tTp/
In case that you want to use data-* properties, you can define an attribute like data-filter='["f1", "f2", ""]' for the elements and use jQuery .data() method for reading them:
$links.removeClass('matched').filter(function () {
return $(this).data('filter').filter(function(f) {
return $.inArray(f, checked) > -1;
}).length === checked.length;
}).addClass('matched');

Build a switch based on array

I want to create a Javascript switch based on an array I'm creating from a query string. I'm not sure how to proceed.
Let's say I have an array like this :
var myArray = ("#general","#controlpanel","#database");
I want to create this...
switch(target){
case "#general":
$("#general").show();
$("#controlpanel, #database").hide();
break;
case "#controlpanel":
$("#controlpanel").show();
$("#general, #database").hide();
break;
case "#database":
$("#database").show();
$("#general, #controlpanel").hide();
break;
}
myArray could contain any amount of elements so I want the switch to be created dynamically based on length of the array. The default case would always be the first option.
The array is created from a location.href with a regex to extract only what I need.
Thanks alot!
#Michael has the correct general answer, but here's a far simpler way to accomplish the same goal:
// Once, at startup
var $items = $("#general,#controlpanel,#database");
// When it's time to show a target
$items.hide(); // Hide 'em all, even the one to show
$(target).show(); // OK, now show just that one
If you really only have an array of selectors then you can create a jQuery collection of them via:
var items = ["#general","#controlpanel","#database"];
var $items = $(items.join(','));
Oh, and "Thanks, Alot!" :)
I think you want an object. Just define keys with the names of your elements to match, and functions as the values. e.g.
var switchObj = {
"#general": function () {
$("#general").show();
$("#controlpanel, #database").hide();
},
"#controlpanel": function () {
$("#controlpanel").show();
$("#general, #database").hide();
},
"#database": function () {
$("#database").show();
$("#general, #controlpanel").hide();
}
}
Then you can just call the one you want with
switchObj[target]();
Granted: this solution is better if you need to do explicitly different things with each element, and unlike the other answers it focused on what the explicit subject of the question was, rather than what the OP was trying to accomplish with said data structure.
Rather than a switch, you need two statements: first, to show the selected target, and second to hide all others.
// Array as a jQuery object instead of a regular array of strings
var myArray = $("#general,#controlpanel,#database");
$(target).show();
// Loop over jQuery list and unless the id of the current
// list node matches the value of target, hide it.
myArray.each(function() {
// Test if the current node's doesn't matche #target
if ('#' + $(this).prop('id') !== target) {
$(this).hide();
}
});
In fact, the first statement can be incorporated into the loop.
var myArray = $("#general,#controlpanel,#database");
myArray.each(function() {
if ('#' + $(this).prop('id') !== target) {
$(this).hide();
}
else {
$(this).show();
}
});
Perhaps you're looking for something like this? Populate myArray with the elements you're using.
var myArray = ["#general","#controlpanel","#database"];
var clone = myArray.slice(0); // Clone the array
var test;
if ((test = clone.indexOf(target)) !== -1) {
$(target).show();
clone.splice(test,1); // Remove the one we've picked up
$(clone.join(',')).hide(); // Hide the remaining array elements
}
here you dont need to explicitly list all the cases, just let the array define them. make sure though, that target exists in the array, otherwise you'll need an if statement.
var target = "#controlpanel";
var items = ["#general","#controlpanel","#database"];
items.splice($.inArray(target, items), 1);
$(target).show();
$(items.join(",")).hide();
items.push(target);

Categories

Resources