Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you group jQuery selectors with (slightly more) advanced logic?

We're working on a filter system, where you get groups of options, for instance:

Colour Red, Blue, Green

Price Range £0-£5, £6-£10, £11+

Make Adidas, Nike, Converse

Each option is a single checkbox. We filter with the following logic:

  • OR options from a group
  • join those with an AND

So, if I was to check Red, Blue, £0-£5, Nike and Converse, the logic would be:

(Red OR Blue) AND (£0-5) AND (Nike OR Converse)

Each checkbox has an ID. I wish to build a selector using the logic above, but I'm unsure about the best way to do it in jQuery. Obviously ANDs are just appended and ORs (or the equivalent) use commands in these selectors, but that would break the logic without some way of grouping, i.e.:

$('(#red,#blue)(#price0to5)(#nike,#converse)')

Any suggestions or alternatives?

like image 547
LeonardChallis Avatar asked Dec 07 '11 10:12

LeonardChallis


People also ask

Which is the fastest selector in jQuery?

ID and Element selector are the fastest selectors in jQuery.

Can we combine multiple selectors in a single jQuery function call?

You can specify any number of selectors to combine into a single result. Here order of the DOM elements in the jQuery object aren't necessarily identical.

Can we use multiple selectors in jQuery?

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.

What is the correct way of selecting the current element with jQuery selectors?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


1 Answers

Let's assume you have a bunch of items with the applicable class identities:

<div class="red nike underfive"></div>
<div class="blue green converse elevenup"></div>
<div class="blue converse underfive"></div>

ORs are equivalent to commas, while ANDs require chaining:

$(".red,.blue").filter(".underfive").filter(".nike,.converse"); // 1 and 3
$(".green").filter(".underfive"); // empty
$(".blue").filter(".green"); // 2
like image 142
Interrobang Avatar answered Sep 20 '22 20:09

Interrobang