Pierre de LESPINAY
Pierre de LESPINAY

Reputation: 46178

jQuery select elements with value between x and y

I'd like to be able to do that kind of selection:

$('input[value between 6 and 11]');

Which would give me the 9 and 10. Is there a way to do that ?

Upvotes: 5

Views: 3523

Answers (3)

jAndy
jAndy

Reputation: 236012

You could use .filter():

$("input").filter(function(){
   var v = parseInt($(this).val());
   return (v > 9 && v < 11)
});

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630389

You can do this with .filter() like this:

$("input").filter(function() { 
  return $(this).val() >= 6 && $(this).val() <= 11; 
}).somethingHere();

If you need to use this often, you could make it a selector as well:

jQuery.expr[':'].between = function(a, b, c) { 
   var args = c[3].split(',');
   var val = parseInt(jQuery(a).val());
   return val >= parseInt(args[0]) && val <= parseInt(args[1]);
};

Then you can select by:

$("input:between(6, 11)")

Just change the >= and <= if you don't want the range to be inclusive.

Upvotes: 15

Darin Dimitrov
Darin Dimitrov

Reputation: 1038780

You could use the filter function:

$('input').filter(function(index) {
    var value = parseInt($(this).val());
    return !isNaN(value) && value > 6 && value < 11;
});

Upvotes: 4

Related Questions