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.
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 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With