Eran Levi
Eran Levi

Reputation: 909

Jquery: "find" of range attributes (Between 2 numbers)

I have an issue with JQuery i couldn't solved..

i have this line:

var $price = $data.find('li[price=' + $max + ']');

That find the Attribute "price" That equal to Var "$max"

Now, basically, I have 2 numbers, $min And $max, And i need that "find" will check if the attribute is between this 2 numbers..

For Example:

  <ul class="ourHolder">
    <li price="200">
    <img src="img1.jpg">
    </li>
    <li price="300">
    <img src="img2.jpg">
    </li>
</ul>

    <script>

// get and assign the ourHolder element to the
    // $holder varible for use later
  var $holder = $('ul.ourHolder');

  // clone all items within the pre-assigned $holder element
  var $data = $holder.clone();
    var $min = 100;
    var $min = 400;
    var $price = $data.find('li[price=' + $max + ']'); //Not sure what to do here
    </script>

Should return both <li> tags.. (Both are Between 100 and 400).

New edit:

I added this:

var price = data.find('li').filter(function() {
   var price = parseInt($(this).data('price')); // i think here it doesn't find nothing
    return price >= minPrice && price <= maxPrice;
}); 

But i returns nothing :(

Thank you!!

Upvotes: 0

Views: 1335

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly you should be using data attributes, as just making up your own attributes will render your code invalid. Secondly you can use filter() to find elements based on a more complex set of rules. Try this:

<li data-price="200">
    <img src="img1.jpg">
</li>
<li data-price="300">
    <img src="img2.jpg">
</li>
var minPrice = 100;
var maxPrice = 400;
var $matchingLi = $data.find('li').filter(function() {
    var price = parseFloat($(this).data('price'));
    return price >= minPrice && price <= maxPrice;
});

Upvotes: 2

Related Questions