2016-11-09 19 views
0

我正在嘗試使用數組做一個簡單的計算onblur,但它不會觸發。如果我將其更改爲跨度或div,則可以正常工作。爲什麼它不與輸入字段一起工作?使用輸入字段而不是跨度或div計算數組

我需要它作爲輸入字段,因爲它更容易將值存儲在數據庫中。

<input type="text" class="input-small" name="partnumber[]"> 
    <input type="text" class="input-small" name="partdescription[]" > 
    <input type="text" class="input-small" name="partprice[]" onblur="doCalc(); calculate(); "> 
    <input type="text" class="input-small" name="partquantity[]" onblur="doCalc(); calculate(); "> 
    <input type="text" readonly class="input-small parttotal" name="parttotal[]" > 

計算

function doCalc() { 
    var total = 0; 

    $('tr').each(function() { 
     $(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val()); 
    }); 
    $('.parttotal').each(function() { 
     total += parseInt($(this).text(),10); 
    }); 
} 
+0

'$( 'TR')each' - 你沒有任何' '您的代碼示例中的元素。這應該指向文本框?或者你錯過了它。請提供一個最小,可驗證,完整的例子:-) – ADyson

回答

0

首先,我不會使用內聯事件。這裏我使用委託的事件,這一優勢在這裏,如果你動態地添加更多的線,它仍然會正常工作。

接下來確保每一行都有某種包裝的每一行,在這裏我使用了一個簡單的DIV。 Yousr可能是您的TR ..

其餘則變得容易,因爲在這裏可以看到,這個例子中,我只是價格,數量&總,並完成2線測試包括..

function calc() { 
 
    var h = $(this).closest('div'); 
 
    var qty = h.find('[name="partquantity[]"]'); 
 
    var price = h.find('[name="partprice[]"]'); 
 
    var total = h.find('[name="parttotal[]"]'); 
 
    total.val(qty.val() * price.val()); 
 
} 
 

 
$('body').on('blur', '[name="partprice[]"],[name="partquantity[]"]', calc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<div> 
 
    <input type="text" class="input-small" name="partprice[]"> 
 
    <input type="text" class="input-small" name="partquantity[]"> 
 
    <input type="text" readonly class="input-small parttotal" name="parttotal[]" > 
 
</div> 
 

 
<div> 
 
    <input type="text" class="input-small" name="partprice[]"> 
 
    <input type="text" class="input-small" name="partquantity[]"> 
 
    <input type="text" readonly class="input-small parttotal" name="parttotal[]" > 
 
</div>

+0

我爲輸入字段添加了更多按鈕,名稱變成了name =「partprice [2] name =」partprice [3] etc等 – JCD

0

不能使用.html()設置文本框的

改變這一行:

$(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val()); 

$(this).find('.parttotal').val($('input:eq(2)', this).val() * $('input:eq(3)', this).val()); 

注意的變化('.parttotal').html變得('.parttotal').val

相關問題