Eva Nebko
Eva Nebko

Reputation: 214

Math.min.apply returns 0

There is five classes "price". The function takes the min number from the class and add it to the "price-box". Every thing works fine exept, when one of the class is empty - the script returs 0. How to fix it?

<div id="price-box"></div>

<table id="table-prices">
 <tr>
    <td>Ткань</td>
    <td>Цена (грн)</td>
 </tr>
 <tr>
   <td>1</td>
   <td class="priсe">1496</td>
 </tr>
 <tr>
   <td>2</td>
   <td class="priсe">4496</td>
 </tr>
 <tr>
   <td>3</td>
   <td class="priсe">2496</td>
 </tr>
 <tr>
   <td>4</td>
   <td class="priсe">5296</td>
 </tr>
 <tr>
   <td>5</td>
   <td class="prise">5696</td>
 </tr>

var array = [];
$('.priсe').each(function(){
    array.push(+$(this).text());
});
console.log(array);
var maximum = Math.min.apply(null,array);
$('#price-box').text(maximum + " грн");

Upvotes: 2

Views: 186

Answers (2)

keune
keune

Reputation: 5795

you can eliminate empty rows by using empty selector.

$('.prise').not(':empty')each(function(){
 // rest of the function
});

as suggested, you can shorten it a bit like this:

$('.prise:not(:empty)') each(function () {
    // rest of the function
});

Upvotes: 2

j08691
j08691

Reputation: 207923

Try checking for an empty value:

$('.prise').each(function(){
    if($.trim($(this).text())!='')array.push(+$(this).text());
});

jsFiddle example

Upvotes: 1

Related Questions