我正在研究計算服務總價格的代碼。添加具有唯一ID的動態輸入字段進行計數
現在,如果我添加小時數(如2)並添加每小時價格(如20),則代碼必須計算將成爲小計的價格。之後,它會計算「BTW」(稅),並將其添加到總價的小計中。
我想要的是添加動態新的輸入字段與唯一的ID,所以代碼可以計算多個服務。因此,對於每項服務,您的總金額合計爲小計。我現在代碼:
HTML
<table class="table-responsive table" id="table-diensten">
<thead>
<tr>
<th>Time</th>
<th>Service</th>
<th>amount</th>
<th>total</th>
<th>BTW</th>
</tr>
</thead>
<tbody class="table-body">
<tr class="table-row">
<td><input type="text" class="form-control" placeholder="time (in hours)" id="time" onchange="totalofferte()"></td>
<td><input type="text" class="form-control" placeholder="service"></td>
<td><input type="text" class="form-control" placeholder="Cost (per hour)" id="cost" onchange="totalofferte()"></td>
<td>€ <span id="total">0,00</span></td>
<td>21%</td>
</tr>
</tbody>
<tfoot>
<tr>
<td> </td>
<td> </td>
<td><strong>Subtotaal</strong></td>
<td>€ <span id="subtotal">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td>21% BTW</td>
<td>€ <span id="costbtw">0,00</span></td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td class="table-total"><span class="total">Totaal</span></td>
<td class="table-total"><span class="total">€ <span id="totalofferte">0,00</span></span></td>
<td> </td>
</tr>
</tfoot>
</table>
<a href="#table-diensten" class="add-tablerow btn btn-default" >add new service</a>
JS
<script type="text/javascript">
function totalofferte() {
var cost = document.getElementById('cost').value;
var time = document.getElementById('time').value;
if (cost > 0 && time > 0) {
var total = cost * time;
if (total > 0) {
document.getElementById('total').innerHTML = total;
var subtotal = total;
if (subtotal > 0) {
document.getElementById('subtotal').innerHTML = subtotal;
var costbtw = subtotal/100 * 21;
document.getElementById('costbtw').innerHTML = costbtw;
var totalofferte = subtotal + costbtw;
document.getElementById('totalofferte').innerHTML = totalofferte;
}
}
}
}
</script>
編輯:
忘記我的JQuery
$(".add-tablerow").click(function(){
$(".table-body").append("<tr class='table-row'><td><input type='text' class='form-control' placeholder='Tijd'></td><td><input type='text' class='form-control' placeholder='Omschrijving'></td><td><input type='text' class='form-control' placeholder='Kosten'></td><td>€ 0,00</td><td>21%</td></tr>");
});
爲什麼不用class而不是id?這將解決您的問題 –
我的問題是,我知道如何添加另一行,但我不知道如何添加一個動態id /類到行中的輸入,所以我可以在我的JS調用它 – Gijsberts
也許在這個答案中的源代碼將幫助你? HTTP://計算器。com/questions/35669941/calulate-function-in-javascript-for-dynamic-added-field/35676764#35676764這個動態創建的元素和計算每個價格與小計。 – NewToJS