1

I have a select with options, its a transformed select not the normal one.

<select>
<option value="0">apple</option>
<option value="1">orange</option>
<option value="2">bannan fruit</option>
</select>

How to find the maximum length in the options(bannan fruit) using Jquery?

Harry
  • 483
  • 4
  • 10
  • 22

3 Answers3

6
var max_length = -1;
$('option').each(function(){
  max_length = Math.max(max_length, $(this).text().length);
});
alert(max_length);
Dogbert
  • 212,659
  • 41
  • 396
  • 397
2

Mandatory one-liner solution:

Math.max.apply(null, $('option').map(function() { return $(this).html().length; }).toArray())

I'd say that Dogbert's solution is probably more readable, but there might still be some fun lessons in here. What's going on:

  • using .map to get a result set of just the lengths
  • using .toArray to make an actual array out of the result set, which would be required by .apply
  • Passing the array to Math.max using apply which will make the second argument the arguments collection, i.e. equivalent of writing Math.max(5, 6, 12);

If you're using Roatin Marth's excellent array extensions, the code would look a bit neater:

Array.prototype.max = function() {
  return Math.max.apply(null, this)
}

$('option').map(function() { return $(this).html().length; }).toArray().max();
Community
  • 1
  • 1
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
  • +1 mandatory up-vote for adequate language feature usage. (`.toArray()` is *correct*, but superfluous, sind the jQuery object actually *is* an array - and I guess it should be `.text()` instead of `.html()`) – Tomalak Dec 14 '11 at 14:16
1

You can prototype jQuery object like this:

jQuery.prototype.select_longest = function () { 
    var res = ""; 
    $(this).children().each(function () {
        if ($(this).html().length > res.length) 
            res = $(this).html(); 
    }); 
    return res;        // use this line if you want biggest string
    return res.length; // use this line if you want length of biggest string
}

Then you can use it like this:

var longest = $("#id").select_longest();