Querying Using Multiple Filter Selectors

Currently, I am in the process of developing a jQuery multiple filter module and have encountered a logic gap in my framework.

Within this module, there are numerous div elements each containing data-x and data-y attributes.

For instance:

<div class="divClass" data-x = "1" data-y="2">1</div>
<div class="divClass" data-x = "2" data-y="3">2</div>
<div class="divClass" data-x = "3" data-y="2">3</div>
<div class="divClass" data-x = "4" data-y="1">4</div>

This setup results in:

Upon selecting the values 2 and 3 for the y attribute along with 1 for the x attribute from the select boxes,

The desired query would be x = 1 and y = 2 or 3

Thus, it should display products

with data-y as 2 or 3 and data-x as 1

thus presenting products 1 and 2

You can view my Fiddle here

$('[data-x="1"],[data-y="2"],[data-y="3"]').each(function(){
    $("#result").append($(this).text() + ",");
});

The current implementation retrieves all products. My inquiry revolves around refining the query within the selector so I may effectively utilize the jQuery filter.

Answer №1

Representation of

((x == 1) && ((y == 2) || y == 3)))
:

$(function(){
  // One approach:
  $('[data-x="1"][data-y="2"],[data-x="1"][data-y="3"]').css('color','red');
  
  // In my opinion, more succinct:
  $('[data-x="1"]').find('[data-y="2"],[data-y="3"]').css('font-weight', '800');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div class="divClass" data-x="1" data-y="1">1-1</div>
<div class="divClass" data-x="1" data-y="2">1-2</div>
<div class="divClass" data-x="1" data-y="3">1-3</div>
<div class="divClass" data-x="2" data-y="1">2-1</div>
<div class="divClass" data-x="2" data-y="2">2-2</div>
<div class="divClass" data-x="2" data-y="3">2-3</div>
<div class="divClass" data-x="3" data-y="1">3-1</div>
<div class="divClass" data-x="3" data-y="2">3-2</div>
<div class="divClass" data-x="3" data-y="3">3-3</div>

(However, based on your query, you were anticipating two matches. I only observe one match with the provided code. To illustrate the match, I've included 9 variations of x/y values)

If you prefer a cleaner solution:

(function($){
  // helper: return jQuery selector based on supplied attribute name.
  var _mapToAttr = function(attr){
    return function(v){ return '[' + attr + '="' + v + '"]'; };
  }
  
  // polyfill: Array.prototype.map
  if (!Array.prototype.map){
    Array.prototype.map = function(func){
      if (this.length == 0) return [];
      var result = [];
      for (var i = 0; i < this.length; i++){
        result.push(func(this[i]));
      }
      return result;
    };
  }
  
  // $.XY(x,y)
  //
  // Params:
  //   @x   = single value or an array of possible values
  //   @y   = single value or an array of possible values
  //
  // Usage:
  //   $.XY(1,2)
  //     Find all elements with an x value of 1 and a y
  //     value of 2.
  //   $.XY(2,[3,4])
  //     Find all elements with an x value of 2 and a y
  //     value of either 3 or 4.
  $.XY = function(x,y){
    // validation: confirm x and y are defined
    if (typeof x === 'undefined' || typeof y === 'undefined') return $([]);
    
    // normalize both values to arrays
    if (!$.isArray(x)) x = [ x ];
    if (!$.isArray(y)) y = [ y ];
    
    // validation: confirm x and y aren't empty sets
    if (!x.length || !y.length) return $([]);
    
    // create jQuery selectors from values
    var xSel = x.map(_mapToAttr('data-x')).join(','),
        ySel = y.map(_mapToAttr('data-y')).join(',');
    
    // return matching sets
    // if a third paramter was supplied, it came from our $.fn.XY()
    // call, therefore use it as an initial context to search within.
    // otherwise, search the entire document for matches.
    var set = arguments.length == 3
      ? $(arguments[2]).filter(xSel).filter(ySel)
      : $(xSel).filter(ySel);
    console.log(set);
    return set;
  };
  
  // $().XY(x,y)
  //
  // Params:
  //   @x = single value or an array of possible values
  //   @y = single value or an array of possible values
  //
  // Usage:
  //   $('.foo').XY(1,2)
  //     Find all elements with the class foo who also
  //      have an X value of 1 and a y value of 2.
  //   $('div').XY([1,2],[3,4])
  //      Find all divs with an x value of either 1 or 2
  //       and a y value of either 3 or 4.
  $.fn.XY = function(x,y){
    // perform above search, but supply an initial context.
    return $.XY(x,y,this);
  };
})(jQuery);

$.XY(1,[2,3]).css('color','red');
$('.divClass').XY(2,[1,3]).css('color','green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<div class="divClass" data-x="1" data-y="1">1-1</div>
<div class="divClass" data-x="1" data-y="2">1-2</div>
<div class="divClass" data-x="1" data-y="3">1-3</div>
<div class="divClass" data-x="2" data-y="1">2-1</div>
<div class="divClass" data-x="2" data-y="2">2-2</div>
<div class="divClass" data-x="2" data-y="3">2-3</div>
<div class="divClass" data-x="3" data-y="1">3-1</div>
<div class="divClass" data-x="3" data-y="2">3-2</div>
<div class="divClass" data-x="3" data-y="3">3-3</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for incorporating additional style attributes into the current settings of a specified component through Component Composition?

Recently, I stumbled upon the Component Composition Design Pattern in React, which my instructor likened to inheritance in OOP. I have a burning question - how can I expand on the predefined props of the Button component? PS: I know usually this could be ...

Angular does not alter the focus when a new component is loaded

Currently, I am working on resolving an accessibility issue with a screen reader in an Angular2 web application. When componentA (code shown below as Before) is loaded in Chrome, the entire browser window gains focus and the screen reader narrator announce ...

Using JQuery, Ajax, and PHP for a secure login system

I need a handler for my login process to verify the username and password in the database and redirect the user to another page if the credentials are correct. I am attempting to achieve this using JQuery Ajax and PHP. I have created a JS script to send t ...

Prevent unauthorized users from accessing the expressjs application

Imagine you have an expressjs app set up like this: var express = require('express'); var http = require('http'); var httpApp = express(); httpApp.configure(function() { httpApp.use(express.static(__dirname + '/static/&apo ...

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

Is there a way for me to showcase information?

I am currently facing an issue with displaying user information retrieved from my database using AngularJS. The code snippet below shows how I am trying to get the user data: angular.module('listController',[]) .controller('listCtrl' ...

How can you use jQuery to select and manipulate multiple form inputs with a common class?

I am currently working on a program that requires at least one of various form inputs to have data in order for the user to submit the form. I was able to successfully code for a scenario with only one input field, but I am facing a challenge when it comes ...

Leverage npm JavaScript packages within an Ionic2 TypeScript project

Just diving into my first project with Ionic2 (TypeScript) and I'm trying to incorporate the npm JavaScript package. Specifically, I am utilizing https://github.com/huttarichard/instagram-private-api I'm a bit confused on how to correctly use im ...

Although PhoneGap resolution remains consistent, the outcomes may vary

I seem to be facing a similar issue as discussed in this post on Stack Overflow: Screen Resolution On A PhoneGap App My problem is that I have both an iPad and an Android tablet, both with a resolution of 1024 pixels across. However, while my screen displ ...

The combination of list-style-type and display:inline is ineffective

Many questions have been asked in different areas about this issue, but none of the answers I found were able to solve my problem. My challenge lies in creating a navigation menu where I can't remove the list style or display it inline. Here is the HT ...

Unable to display content in div using jQuery ajax function

I am currently working on a script called support_question.php $('#topic').on('change', function() { var sel = $(this).find('option:selected').val(); $.ajax({ url: "support_process.php", type: "POST" ...

Creating Angular directives: dynamically applying ng-class directive to template elements during compilation

In short, the aim is to streamline templating by avoiding manual addition of ng-class={'has-error': 'formName.inputName.$invalid'} for every individual form-group The idea is to develop a directive that will automatically generate a st ...

Using the factory pattern in a Node.js (Express) application

As I delved into the realm of design patterns, I found myself drawn to the factory pattern. However, as I perused through code written by others, I noticed that this particular pattern wasn't as prevalent, especially in newer stacks. Take for example ...

Encountering an undefined json array when making an AJAX request

There have been numerous questions on this topic, but none of the specific solutions seemed to apply to my situation. So, I apologize if this is a duplicate query. I am currently working on fetching data from an SQL database using a PHP file that passes t ...

What is the best way to ensure that text fields remain hidden upon page load until the appropriate drop down option is chosen?

Is it possible to initially hide text fields and only reveal them when a specific drop down option is selected? The current JavaScript code somewhat achieves this, but I would like the input fields to remain hidden by default. <script language=" ...

Reverse the order of jQuery toggle animations

Looking for something specific: How can I create a button that triggers a script and then, when the script is done, reverses the action (toggles)? (I am currently learning javascript/jquery, so I am a beginner in this field) Here's an example: ...

Node.JS guide on handling geonames city information

While unconventional, I wanted to share my solution since there is a lack of information on how to accomplish this task on the stack. After searching for an easy-to-use Node.JS module to process geonames data into a mongo database, I found very few project ...

Create an HTML table to view JSON data from a cell on a map

Looking to transform the JSON data into a table by organizing the information based on supplier and product. Below is the JSON input and code snippet: $(document).ready(function () { var json = [{ "Supplier": "Supplier1", "Product": "O ...

Here is a guide on how to interact with a flash object by clicking

I'm trying to click on a flash object using javascript, but my current code doesn't seem to be working. I don't have a lot of experience with javascript, so please be patient with me. JavascriptExecutor js = (JavascriptExecutor) driver; js. ...

Issue with dragging and styling windows in Safari on iOS

When checking my website on Safari using an iPad or iPhone, I noticed that I can touch and drag left to right, causing the entire window to move and reveal the grey background behind it. Here is a link to my page. However, when visiting other websites, no ...