2016-10-21 5 views
-2

У меня есть calculation table, и сумма становится NaN после добавления 10 строк. Я даже попробовал предложения, как указано в этом Stackoverflow article. Я тестировал это уже более суток и не могу исправить ошибку. Что мне не хватает?Итого становится NaN после приращения 10

jQuery(document).ready(function($){ 
 
    var counter = 2; 
 

 
    $("#addItem").click(function() { 
 
    
 
     if(counter>50){ 
 
       alert("You have reached the maximum items allowed (50)!"); 
 
       return false; 
 
     } 
 
     
 
     var newTextBoxDiv = $(document.createElement('tr')) 
 
      .attr("id", 'itemRow' + counter); 
 
     
 
     newTextBoxDiv.after().html('<td class="first"><input placeholder="Charge # ' + counter + '" class="chrg" type="text" name="data[' + counter + '][0]" id="chrg' + counter + '" ></td>' + '<td><input placeholder="Item/Part # ' + counter + '" class="item" type="text" name="data[' + counter + '][1]" id="item' + counter + '" ></td>' + '<td><input placeholder="Description ' + counter + '" class="desc" type="text" name="data[' + counter + '][2]" id="desc' + counter + '" ></td>' + '<td style="text-align:center;"><input placeholder="Qty ' + counter + '" class="qty" type="text" name="data[' + counter + '][3]" id="qty' + counter + '" size="5" style="text-align:center;" /></td>' + '<td style="text-align:right;"><input placeholder="Cost ' + counter + '" class="cost" type="text" name="data[' + counter + '][4]" id="cost' + counter + '" size="10" style="text-align:right;" /></td>' + '<td style="text-align:right;"><span class="input-group-addon">$</span><input placeholder="Sub-Total ' + counter + '" class="stotal" type="text" name="stotal'+ counter + '" id="stotal'+ counter +'" size="10" style="text-align:right;" readonly /></td>'); 
 
     
 
     newTextBoxDiv.appendTo("#TextBoxesGroup"); 
 
     
 
     counter++; 
 
    }); 
 

 
    $(document).on('keyup', '.cost', function(st){  
 
     // grab ID to get row number 
 
     thisID = $(this).attr("id"); 
 
     rowNum = thisID.slice(-1); 
 
     
 
     //get Amount entered 
 
     qty = $('#qty'+rowNum).val(); 
 
     //get QTY 
 
     cost = $('#cost'+rowNum).val();   
 
     $('#stotal'+rowNum).val((qty*cost).toFixed(2)); 
 
     
 
     currentCount = counter-1; 
 
     var tot = Math.round(0); 
 
     $('.stotal').each(function() { 
 
      tot += parseFloat($(this).val());    
 
     }); 
 
      
 
\t $('#preTotal').val((tot).toFixed(2)); 
 
\t $('#grand_total').val((tot).toFixed(2)); 
 
    }); 
 
\t 
 
//calculate preTotal 
 
    $(document).on('focusin', '#shipping', function(pt){ 
 
\t var selection = document.getElementById("addShip"); 
 
\t \t if (selection.checked){ 
 
\t \t $("#shipping").change(function(preTotal,shipping) { // input on change 
 
\t \t var preTotal = document.getElementById('preTotal').value; 
 
    \t \t var shipping = document.getElementById('shipping').value || 0; 
 
\t \t var pTotal = parseFloat(shipping) + parseFloat(preTotal); \t \t 
 
\t \t 
 
\t \t document.getElementById('preTotal').value = (pTotal.toFixed(2)); 
 
\t \t }); 
 
\t \t } else { 
 
\t \t var preTotal = document.getElementById('preTotal').value; 
 
    \t \t var shipping = document.getElementById('shipping').value || 0; 
 
\t \t var sTotal = parseFloat(preTotal); \t \t 
 
\t \t 
 
\t \t document.getElementById('preTotal').value = (sTotal.toFixed(2)); 
 
\t \t } 
 
\t }); 
 

 
//calculate taxes and total 
 
    $(document).on('focusin', '#taxTotal', function(tt){ 
 
\t var selection = document.getElementById("addShip"); 
 
\t \t //get field results \t \t 
 
\t \t var preTotal = document.getElementById('preTotal').value || 0; 
 
\t \t var shipping = document.getElementById('shipping').value || 0; 
 
\t \t var taxTotal = document.getElementById('taxTotal').value || 0; 
 
\t \t var taxRate = document.getElementById('taxRate').value || 0; 
 
\t \t var gTotal = document.getElementById('grand_total').value || 0; 
 

 
\t \t $("#taxTotal").change(function() { // input on change 
 
\t \t var tTotal = document.getElementById('taxTotal').value/document.getElementById('preTotal').value * 100; 
 
\t \t document.getElementById('taxRate').value = (tTotal.toFixed(2)); 
 
\t \t }); 
 

 
    }); 
 
\t 
 
//calculate total + taxes 
 
    $(document).on('focusout', '#taxTotal', function(gt){ 
 
\t \t var shipping = document.getElementById('shipping').value || 0; 
 
\t \t var tTotal = document.getElementById('taxTotal').value || 0; 
 
\t \t var gTotal = document.getElementById('grand_total').value; 
 
\t \t var fTotal = parseFloat(shipping) + parseFloat(tTotal) + parseFloat(gTotal); 
 
\t \t document.getElementById('grand_total').value = (fTotal.toFixed(2)); 
 
    }); 
 

 
}); 
 

 
} 
 

 
function focusField() { 
 
    $('#addItem').click(function(){ 
 
    $('.chrg').focus(); 
 
\t });
th \t \t \t \t {padding: 2px 2px;} 
 
td \t \t \t \t {padding: 2px 2px;} 
 
input \t \t \t {padding: 0px 2px;} 
 
#addItemBtn \t {} 
 
input.filler \t {border-color:#fff;border-style:solid;} 
 
.input-group-addon { 
 
    padding: 2px 5px; 
 
    font-size: 14px; 
 
    font-weight: 400; 
 
    line-height: 1; 
 
    color: #555; 
 
    text-align: center; 
 
    background-color: #eee; 
 
\t box-shadow: inset 0 0 0 1px grey; 
 
\t border-right: 1px #eee solid; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<table id="TextBoxesGroup" style="width:100%;"> 
 
    <tr> 
 
    \t \t <th style="text-align:left;">Charge #</th> 
 
     <th style="text-align:left;">Item/Part #</th> 
 
     <th style="text-align:left;">Description</th> 
 
     <th style="text-align:center;">Qty</th> 
 
     <th style="text-align:right;">Cost</th> 
 
     <th style="text-align:right;">Sub-total</th> 
 
    </tr> 
 
    <tr id="itemRow1"> 
 
     <td><input placeholder="Charge # 1" class="chrg" type="text" id="chrg1" autofocus /></td> 
 
     <td><input placeholder="Item/Part # 1" class="item" type="text" id="item1" style="margin-bottom:0 !important" /></td> 
 
     <td><input placeholder="Description 1" class="desc" type="text" id="desc1" /></td> 
 
     <td style="text-align:center;"><input placeholder="Qty 1" class="qty" type="text" id="qty1" size="5" style="text-align:center;" /></td> 
 
     <td style="text-align:right;"><input placeholder="Cost 1" class="cost" type="text" id="cost1" size="10" style="text-align:right;" /></td> 
 
     <td style="text-align:right;"><span class="input-group-addon">$</span><input placeholder="Sub-Total 1" class="stotal" type="text" id="stotal1" size="10" style="text-align:right;" readonly /></td> 
 
    </tr> 
 
</table> 
 
<table style="width:100%;"> 
 
    <tr id="rowFiller"> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td><input class="btn btn-primary" type="button" id="addItem" value="Add Item" size="10" style="float:right;" onclick="focusField()" /></td> 
 
    </tr> 
 
    <!--<tr id="addItemBtn"> 
 
     \t <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td><input type="button" id="addItem" value="Add Item" style="float:right;" /></td> 
 
    </tr>--> 
 
    <tr> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td style="text-align:right;"> 
 
     <label style="padding-right:5px;">remove shipping from taxable total 
 
     <input type="checkbox" id="addShip" class="addShip" name="addShip" checked ></label> 
 
     </td>  
 
    </tr> 
 
    <tr> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td style="text-align:right;"> 
 
     <label style="font-weight:bold;padding-right:5px;display:inline-block;">Shipping</label> 
 
     <span class="input-group-addon">$</span> 
 
     <input placeholder="$00.00" name="shipping" id="shipping" size="10" style="float:right;text-align:right;" /> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td></td> 
 
     <td></td> 
 
     <td style="text-align:right;"> 
 
     <label style="font-weight:bold;padding-right:5px;display:inline-block;">Pre-Total</label> 
 
     <input name="preTotal" id="preTotal" size="10" style="float:right;text-align:right;" readonly /></td> 
 
     <td></td> 
 
     <td> 
 
     </td> 
 
     <td style="text-align:right;"> 
 
     <div style="text-align:right;display:inline;border-right:1px #ccc solid;margin-right:5px;"> 
 
     <label style="font-weight:bold;padding-right:5px;display:inline-block;">Tax</label> 
 
     <input placeholder="00" class="taxRate" name="taxRate" id="taxRate" size="1" style="text-align:center;" /> 
 
     <label style="font-weight:bold;display:inline-block;">%</label> 
 
     </div> 
 
     <label style="font-weight:bold;padding-right:5px;display:inline-block;">Total Tax</label> 
 
     <span class="input-group-addon">$</span><input placeholder="$00.00" name="taxTotal" id="taxTotal" size="10" style="float:right;text-align:right;" /> 
 
     </td> 
 
    </tr> 
 
    <tr> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td></td> 
 
     <td style="text-align:right;font-weight:bold;"><label style="font-weight:bold;padding-right:5px;display:inline-block;">Grand Total</label> 
 
     <span class="input-group-addon">$</span><input placeholder="$00.00" name="grand_total" id="grand_total" size="10" style="float:right;text-align:right;" readonly /></td> 
 
    </tr> 
 
</table>

+0

Пожалуйста, добавьте тег языка, на котором вы программируете/создаете сценарий, на вопрос. – progyammer

+3

Вам действительно нужно уменьшить эту проблему до меньшего количества кода. Я серьезно сомневаюсь, что число становится NaN после добавления 10 к нему. Скорее, сценарий - это номер, который, по вашему мнению, был реальным, на самом деле NaN, тогда вы добавляете к нему 10. – Carcigenicate

+2

Упс, понял, что я неправильно понял проблему. Предложение все еще стоит. Здесь много кода, и я сомневаюсь, что 90% его даже имеет значение. – Carcigenicate

ответ

0

Добавить ниже условия для вашего кода, прежде чем на самом деле разбора значений с плавающей точкой.

if(preTotal === ""){ 
    preTotal = 0; // assign number value you like 
} 

и

if(gTotal === ""){ 
    gTotal = 0; // here also. 
} 

Потому что, в первый раз, эти значения получены в виде пустых строк.

Кроме того, я заметил, что здесь происходит мероприятие «focusin». Он запускает обработчик каждый раз, когда пользователь идет, чтобы положить что-то внутри тестового окна.

+0

Я добавил if (preTotal) под выбор var и если (gTotal) в функции (gt) и дал те же результаты. –

+0

Я также удалил обработчики событий для события focusin. Попробуйте это сделать. – gkb

+0

Не могли бы вы создать скрипку? –

 Смежные вопросы

  • Нет связанных вопросов^_^