vellai durai vellai durai - 5 months ago 21
Javascript Question

find minimum and maximum value in attribute using jquery

I need to find minimum and maximum value in data attribute but it returns 0

here is my code

<div data-price="2" class="maindiv">test</div>
<div data-price="5" class="maindiv">test</div>
<div data-price="3" class="maindiv">test</div>
<div data-price="0" class="maindiv">test</div>
<div data-price="25"class="maindiv">test</div>
<div data-price="10" class="maindiv">test</div>

<script>
var ids = $("div[data-price]").map(function() {
return this.id;
}).get();

var highest = Math.max.apply( Math, ids );
var lowest = Math.min.apply( Math, ids );

alert(highest)
alert(lowest)
</script>

Answer

Currently you are returning the id attribute from the map function. Change it to to data-price

var ids = $("div[data-price]").map(function() {
  return $(this).data("price");
}).get();
var highest = Math.max.apply( Math, ids );
var lowest = Math.min.apply( Math, ids );
alert(highest)
alert(lowest)

Fiddle