Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector for attributes with values greater than or less than an amount using > or <

I have a few div elements like:

<div class="roomnamecta" data-price="1189" data-adult="3">Room 1</div>
<div class="roomnamecta" data-price="578" data-adult="1">Room 2</div>
<div class="roomnamecta" data-price="650" data-adult="2">Room 3</div>

In jQuery I'm able for example to display div which data-adult= a specific value

// init (first I'm hiding all my divs)
$('.roomnamecta').hide();
// now I'm just showing depending on "data-adult" value
$('.roomnamecta[data-adult="3"]').show();

What I would like to do is something like this:

$('.roomnamecta[data-adult>="3"]').show();
// doesn't work

And better what I want to accomplish is to do for example:

$('.roomnamecta[data-adult>="3"],.roomnamecta[data-price>="1100"]').show();

How to write such a query, do I have to use object? How?

like image 226
user367864 Avatar asked Mar 04 '15 18:03

user367864


People also ask

Can you use a variable in a jQuery selector?

Yes, it is possible to pass a variable into a jQuery attribute-contains selector. The [attribute*=value] selector is used to select each element with a specific attribute and a value containing a string.

Does jQuery support selection based on attributes values?

jQuery [attribute|=value] Selector The [attribute|=value] selector selects each element with a specified attribute, with a value equal to a specified string (like "en") or starting with that string followed by a hyphen (like "en-us"). Tip: This selector is often used to handle language attributes.

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

Since you can't accomplish this with an attribute selector (like you're trying to do), you would have to iterate over the elements and check.

For instance, you could use the .filter() method to return the elements whose data-adult attribute value is greater than or equal to 3:

Example Here

$('.roomnamecta[data-adult]').filter(function () {
    return $(this).data('adult') >= 3;
}).show();

For your second query, you could use:

Example Here

$('.roomnamecta[data-adult], .roomnamecta[data-price]').filter(function () {
    return $(this).data('adult') >= 3 || $(this).data('price') >= 1100;
}).show();
like image 77
Josh Crozier Avatar answered Nov 10 '22 00:11

Josh Crozier