0

I am having many textboxes, every textbox has some value in it. I want to get the maximum value from all of the textboxes. I don't know which jQuery I should apply in this. Please take a look at my try below:

$(document).ready(function(){
  $("p").click(function(){
    $('input[name="result"]').val(Math.max('input[name^="tt"]'));
  });
});

//it should give 76.4
<input name='tt1' value='12.2'><br>
<input name='tt1' value='33.2'><br>
<input name='tt1' value='24.2'><br>
<input name='tt1' value='76.4'><br>
<input name='tt1' value='34.3'><br><br>
<input name='result'>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Rahul Dev
  • 71
  • 5
  • What is `Math.max()` supposed to do with a string (`Math.max('input[name^="tt"]')`)? o.O – Andreas Jul 26 '21 at 08:21
  • Get all values, parse them into actual numbers and then use `Math.max()` – Andreas Jul 26 '21 at 08:22
  • Dupe (concept) of: [Finding the max value of an attribute in an array of objects](https://stackoverflow.com/questions/4020796/finding-the-max-value-of-an-attribute-in-an-array-of-objects) – Andreas Jul 26 '21 at 08:43
  • Sir, please remove your vote down, because StackOverflow will stop my question asking if my question received negative votes. Please sir, remove your vote down. – Rahul Dev Jul 26 '21 at 11:24

2 Answers2

1

$("button").click(function() {
  var allValues = $('input[name^="tt"]').map(function() { return +this.value; }).toArray();
  var maxValue = Math.max.apply(Math, allValues);
  $('input[name="result"]').val(maxValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input name='tt1' value='12.2'><br>
<input name='tt1' value='33.2'><br>
<input name='tt1' value='24.2'><br>
<input name='tt1' value='76.4'><br>
<input name='tt1' value='34.3'><br><br>
<input name='result'><button>Click</button>

Notes

  • +'12.2' is 12.2
  • X.y.apply(Y, [1, 2, 3]) is X.y(1, 2, 3) (see)
Tomalak
  • 332,285
  • 67
  • 532
  • 628
0

You can do it with an iteration:

let items = $('input[name^="tt"]');
let max;
for (let item of items) {
    let currentItem = parseFloat(item.value);
    if ((max === undefined) || (max < currentItem)) max = currentItem;
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175