renakre renakre - 7 months ago 12
HTML Question

How to search via data attribute based on a numeric value and get the closest value

I have a unordered list of divs with different

data-score
values. What I am trying to access the first div with
data-score
just above the value of the searched value. I have the following code, but it does not seem to work. Any suggestions?



var userscore = $("#userScore").val();

var next = $("div[data-score >=" + userscore + "]").text();

$("#result").text(next);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="hidden" id="userScore" value="20">
<div data-score="5" class="item">A</div>
<div data-score="15" class="item">B</div>
<div data-score="45" class="item">E</div>
<div data-score="25" class="item">C</div>
<div data-score="35" class="item">D</div>


<div id="result">NEXT IS UNKNOWN!</div>




Answer

Use .filter() to reduce set of elements as per the condition specified in the handler.

Apply .sort() over elements returned by .filter and get the .first() element out of it!

var userscore = $("#userScore").val();
var next = $("div[data-score]").filter(function() {
  return $(this).data('score') >= userscore;
}).sort(function(a, b) {
  return Number($(a).data('score')) - Number($(b).data('score'));
}).first();

$("#result").text(next.text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="hidden" id="userScore" value="20">
<div data-score="5" class="item">A</div>
<div data-score="15" class="item">B</div>
<div data-score="45" class="item">E</div>
<div data-score="25" class="item">C</div>
<div data-score="35" class="item">D</div>
<hr>
<div id="result">NEXT IS UNKNOWN!</div>