Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get highest number from table cell content

Tags:

jquery

I'm trying to get the highest number (8 in example below) from the table cells with specific class. I'm assuming I'll have to convert it to an array and then do math.max on it?

This is my HTML code:

<table>
    <tr>
        <td class="id">3</td>
    </tr>
    <tr>
        <td class="id">8</td>
    </tr>
    <tr>
        <td class="id">4</td>
    </tr>
</table>

This is really what I've tried, but it just returns 384. So math.max doesn't work on it.

var varID = $('.id').text();
var varArray= jQuery.makeArray(varID);
alert (varArray);
like image 968
zen Avatar asked Sep 23 '12 22:09

zen


People also ask

How do you select the highest value in SQL?

The MAX() function returns the largest value of the selected column.

How do I get the maximum value from another column of a table in SQL?

In SQL Server there are several ways to get the MIN or MAX of multiple columns including methods using UNPIVOT, UNION, CASE, etc… However, the simplest method is by using FROM … VALUES i.e. table value constructor. Let's see an example. In this example, there is a table for items with five columns for prices.


3 Answers

I think the best way would be:

var max = 0;
$('.id').each(function()
{
   $this = parseInt( $(this).text() );
   if ($this > max) max = $this;
});
alert(max);

jsfiddle example

like image 60
Undefined Avatar answered Nov 14 '22 16:11

Undefined


Try this:

var high = Math.max.apply(Math, $('.id').map(function(){
         return $(this).text()
}))

http://jsfiddle.net/9mQwT/

like image 31
undefined Avatar answered Nov 14 '22 17:11

undefined


Check this FIDDLE

$(function() {

   // Get all the elements with class id
   var $td = $('table .id');
   var max = 0;
    $.each($td , function(){
        if( parseInt($(this).text()) > max){
           max = parseInt($(this).text())
        }
    });
            console.log('Max number is : ' + max)

});​

You can use parseInt or parseFloat to convert it to a number otherwise , it will compare them like strings with their ascii values..

like image 37
Sushanth -- Avatar answered Nov 14 '22 17:11

Sushanth --