Harry
Harry

Reputation: 489

how to find the maximum length of an option using jquery

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?

Upvotes: 1

Views: 3089

Answers (3)

robert petranovic
robert petranovic

Reputation: 341

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();

Upvotes: 1

Dogbert
Dogbert

Reputation: 222128

var max_length = -1;
$('option').each(function(){
  max_length = Math.max(max_length, $(this).text().length);
});
alert(max_length);

Upvotes: 6

David Hedlund
David Hedlund

Reputation: 129792

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();

Upvotes: 2

Related Questions