I have few input fields with class name scores
, their ids are random and for sure the input fields are dynamic but with the same class name.
<input type="text" class="scores" id="1dhs3d" value="50">
<input type="text" class="scores" id="ae34bd" value="100">
<input type="text" class="scores" id="6ydbbd" value="15">
How do i get the id (in this case, it's ae34bd) of input that has the highest value.
Note: it's possible i have elements with more than one "same high score"
I have tried this:
var max_=[];
$('.scores').each(function(){ max_.push( $(this).val() ); });
var max = Math.max.apply(Math, max_);
With this, can only get the highest value but i need to know the id of element that has that highest value.
As I know you got the answer already, But I have done this in JavaScript and to get if there are multiple fields with the same highest value.
let elements = document.getElementsByClassName('scores'); elements = [...elements]; console.log(...elements) let max = Math.max.apply(Math, elements.map(e=>Number(e.value))) console.log(max) let allMaxIds = elements.filter(e=>{ return max === Number(e.value); }).map(e=> {return {id:e.id,score:Number(e.value)}}); console.log(allMaxIds)
<input type="text" class="scores" id="1dhs3d" value="50"> <input type="text" class="scores" id="ae34bd" value="100"> <input type="text" class="scores" id="ae34bb" value="100"> <input type="text" class="scores" id="6ydbbd" value="15">
Here is an option using sorting from the Array object:
let scores = Array.from($(".scores")); let sortedElements = scores.sort((a, b) => parseInt($(b).val()) - parseInt($(a).val())); let $max = $(sortedElements[0]); console.log("Element id with highest score: #" + $max.attr('id'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="scores" id="1dhs3d" value="50"> <input type="text" class="scores" id="ae34bd" value="100"> <input type="text" class="scores" id="6ydbbd" value="15"> <input type="text" class="scores" id="6ydb2d" value="15">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.