Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding Closest Matching Value using jQuery or javascript

Consider a markup such as

<select id="blah">
  <option value="3">Some text</option>
  <option value="4">Some text</option>
  <option value="8">Some text</option> // <---- target this tag based on value 7
  <option value="19">Some text</option>
</select>

Suppose I have a value with me, say 7. Is it possible to target the option tag whose value attribute is closest to 7 which, in this case, would be <option value="8">?

I'm aware of ^ which means starting with and $ which means ending with and was hoping if there is something like this to find the closest match for a given value.

like image 521
asprin Avatar asked Jan 10 '13 10:01

asprin


1 Answers

I'll go like this:

http://jsfiddle.net/GNNHy/

var $tmpOption = $('<option value="7">Some text 7</option>');
$("#blah").append($tmpOption);
var my_options = $("#blah option");
my_options.sort(function(a,b) {
    if (parseInt(a.value,10) > parseInt(b.value,10)) return 1;
    else if (parseInt(a.value,10) < parseInt(b.value,10)) return -1;
    else return 0
})

$("#blah").empty().append( my_options );
like image 91
A. Wolff Avatar answered Nov 14 '22 13:11

A. Wolff