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.