Thomas Westby
Thomas Westby

Reputation: 33

Get max from series of input fields

I have a series of input fields. I never know how many, so I need to get the value from a class. In this case the class is .total.

The bestresult is a text field that gets it's value from mysql, but I want it to be changed manually or by the highest value from the other text fields.

This is the code. Does not work obviously, but maybe you get the idea of what I want to do.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$('input.total').change(function()
{
    var max = $('.total').max();
    $('#bestresult').attr("value", max);
});
</script>
<body>
<form>
<input type="text" name="bestresult" id="bestresult" class="total" value=""><br>
<input type="text" name="resultat[100][total]" class="total" value=""><br>
<input type="text" name="resultat[121][total]" class="total" value=""><br>
<input type="text" name="resultat[130][total]" class="total" value="">
</form>
</body>
</html>

Upvotes: 3

Views: 423

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382122

First, you should have your script at the end of your body, in order to have the elements defined when you bind the change event.

Then, you'd better filter the input, to exclude the one containing the max. You can use this selector : input.total[id!=bestresult].

And it would be better to bind also the keyup event, so that the max is updated without the user having to click outside.

Thus, you can have this code :

$('input.total[id!=bestresult]').on('blur change keyup', function(){
    $('#bestresult').attr("value", Math.max.apply(null, $('.total[id!=bestresult]').map(function(){
        return parseFloat(this.value)}).slice().filter(function(i, v){return v==v})
    ));
});

Demonstration

Upvotes: 2

phnkha
phnkha

Reputation: 7872

The solution is very simple. Try this:

$('input.total').change(function()
{
     var max = 0;

     $('.total').each(function(){
          if(parseFloat($(this).val()) > max ) {
               max = parseFloat($(this).val());
          }
     });

     $('#bestresult').val(max);
});

But if you have multiple textboxes, you should keep track of the max value and update every time change event is triggered to achieve better performance.

    var max = 0;

    // get the max for the first time
    $(document).ready(function () {
        $('.total').each(function () {
            if (parseFloat($(this).val()) > max) {
                max = parseFloat($(this).val());
            }
        });

        $('#bestresult').val(max);
    });

    $('input.total').change(function () {
        if (parseFloat($(this).val()) > max) {
            max = parseFloat($(this).val());
        }

        $('#bestresult').val(max);
    });

Upvotes: 3

Related Questions