Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the maximum value in a drop-down list using jQuery?

Tags:

jquery

I have a drop-down list with numerical values:

<select name="a">
   <option value="1">asdsadas</option>
   <option value="1">wqecsdc</option>
   <option value="10">nmnmbn</option>
   <option value="16">assadsa</option>
   <option value="12">uuyuyuy</option>
   <option value="60">xzXz</option>
   <option value="55">vbbnbnm</option>
   <option value="13">eerrt</option>
</select>

I need to find the highest numerical value within this list. (In this case, it's 60.)

I was thinking of looping using .each, but is there a shorter way?

like image 283
Elitmiar Avatar asked Apr 22 '10 15:04

Elitmiar


2 Answers

This works fine for me, pretty straight forward:

$('select option:last').val()

edit: misunderstood the question but might become handy for others, in most cases you have the options in the select element ordered desc or asc.

like image 103
Frankey Avatar answered Oct 12 '22 22:10

Frankey


Something like this should work:

function findMaxValue(element) {
    var maxValue = undefined;
    $('option', element).each(function() {
        var val = $(this).attr('value');
        val = parseInt(val, 10);
        if (maxValue === undefined || maxValue < val) {
            maxValue = val;
        }
    });
    return maxValue;
}

alert(findMaxValue($('select[name=a]')));
like image 43
Ken Browning Avatar answered Oct 13 '22 00:10

Ken Browning