6

I have a number of input[type=text] fields on my page and I want to loop through all of them in order to find and return the highest value.

Is there a way to do this with jQuery?

Thanks for any help.

1

2 Answers 2

13

Here is one solution:

var highest = -Infinity;
$("input[type='text']").each(function() {
    highest = Math.max(highest, parseFloat(this.value));
});
console.log(highest);

Here is another solution:

var highest = $("input[type='text']").map(function() {
    return parseFloat(this.value);
}).get().sort().pop();

console.log(highest);
Sign up to request clarification or add additional context in comments.

4 Comments

No reason for a duplicate answer... +1
And how about this? highest = Math.max(highest, this.value*1); for avoid non-numeric values and NaN
$(...).map(...).sort(...).pop is not a function
@vee Back to 2012 map() was returning array-like jQuery collection object with array prototype methods. Now we have to be strict and use get() to receive pure JavaScript array from jQuery collection. Please see the updated answer.
5

Use Math.max function:

var nums = [];
$("input[type=text]").each( function() { nums.push( $(this).val() ); });
var max = Math.max.apply(Math, nums);

1 Comment

Thanks for your help. Will try this one as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.