0

I'm trying to use JQuery's not selector with the eq selector with variables to filter a list of items based on search criteria.

I have a list of products adjacent to a list of prices. I also have a search field, where you can search by product or price. My goal, is for when someone searches for a specific product, for only that product to show and the rest of the products to be hidden.

Here is my code.

var numItems = 5;

// When the search button is clicked
$("#search-btn").click(function() {
        // As long as the search field has a value
        if ($("#search-field").val() !== "") {
            var productsArray = [];
            for (var i = 0; i < numItems; i++) {
                // If the product name equals the search field value add to
                // the array
                if (products[i] == $("#search-field").val()) {
                    productsArray.push(products[i]);
                }
            }
            // Get the index of the product
            var pos = products.indexOf(productsArray[0]);
            $("#products-list > li:not(:eq(pos - 1)),
            #price-list > li:not(:eq(pos - 1))").hide();
        }
    });

My code works if I have a numeric value inside the eq selector (i.e. 2), but not when I place a variable inside. Here is the specific line.

$("#products-list > li:not(:eq(pos - 1)), #prices-list > li:not(:eq(pos - 1))").hide();

#products-list and #prices-list are the names of my lists of products and prices respectively. I'm using the direct child selector > to find all the list elements of these lists. I'm then trying to select the list items that do not match the search criteria and hide them. That way, only the search list items are shown.

I need to know how I can place a variable inside a jquery selector.

Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87

1 Answers1

-1

It looks to me like you just need to use a concatenator:

$("#products-list > li:not(:eq(" + (pos - 1) + ")), #prices-list > li:not(:eq(" + (pos - 1) + "))").hide();

Hope this helps!

wrxsti
  • 3,434
  • 1
  • 18
  • 30
  • Add parentheses around ``pos - 1`` otherwise you'll be evaluating something like ``"#products-list > li:not(:eq(0" - 1``. The reason I know this: [``Array(16).join("wat" - 1) + " Batman!"``](https://www.destroyallsoftware.com/talks/wat) – Patrick Roberts May 15 '15 at 18:43
  • If it is part of a string this is typically not the case, but I do like to do that as a good practice anyways. – wrxsti May 15 '15 at 18:44