user3395842
user3395842

Reputation:

Find the smallest value of a table row using javascript

Ok currently I'm using this code to find it but I need to filter out null fields so that all my cells that are blank don't turn red.

$('tr').each(function highlight() {
    var $td = $(this).children('td');

    // find all the values
    var vals = $td.map(function () {
            return +$(this).text();
        }).filter(function (val) {
            return val !== null
        });
}).get();

// then find their minimum
var min = Math.min.apply(Math, vals);

// tag any cell matching the min value
$td.filter(function highlight() {
    return +$(this).text() === min;
}).addClass('alert alert-danger');
});

So how do I filter out the null values?

Upvotes: 0

Views: 2974

Answers (3)

AbhinavRanjan
AbhinavRanjan

Reputation: 1646

var rows = $("tr");
var minValArray = new Array();
for(var i = 0; i < rows.length; i++) {
    var row = rows[i];
    var elements = $(row).find("td");
    var min = 9999999999; // make this larger than other numbers in your table
    for(var j = 0; j < elements.length; j++) {
        if(!isNaN(parseInt($(elements[j]).text())) && parseInt($(elements[j]).text()) < min)
             min = parseInt($(elements[j]));
    }
    minValArray.push(min);
}

This should give minimum of all the rows in an array.

Upvotes: 0

sabithpocker
sabithpocker

Reputation: 15566

if $('#asd').text() evaluates to ""

then +$('#asd').text() will evaluate to 0


To find minimum in whole table

http://jsfiddle.net/6DgAW/

var vals = $('tr td').map(function () {
    return isNaN(parseInt($(this).text(), 10)) ? parseInt($(this).text(), 10) :  null;
}).get();

// then find their minimum
var min = Math.min.apply(Math, vals);

// tag any cell matching the min value
$('tr td').filter(function () {
    return parseInt($(this).text(), 10) === min;
}).addClass('alert alert-danger');

To find minimum in each row

http://jsfiddle.net/DggUN/18/

$('tr').each(function(){
    var vals = $('td,th',this).map(function () {
        return parseInt($(this).text(), 10) ? parseInt($(this).text(), 10) :  null;
    }).get();
    // then find their minimum
    var min = Math.min.apply(Math, vals);

    // tag any cell matching the min value
    $('td,th', this).filter(function () {
        return parseInt($(this).text(), 10) === min;
    }).addClass('alert alert-danger');
});

Upvotes: 2

Amarnath R Shenoy
Amarnath R Shenoy

Reputation: 5201

I havent tested this code

   var min=0; 
   $("tr").each(function(e){
     var tr = $(this);
     var valuses =$(this).find(".YourClassNameForTheParticularfield").html(); 
     if(!isNaN(Number(Values))) //NullChecking
     {
        if(min>Number(mark));
          {
            min = mark;
          }
      }
   });

isNaN checks whether it is not a number which includes null or text , Using isNaN may solve your issue

Upvotes: 0

Related Questions