現在我的代碼非常「硬編碼」和重複。我想知道是否有更乾淨的方法來做到以下幾點。理想情況下,我想通過循環遍歷表單字段並用一條語句計算結果,但我正在努力弄清楚如何做到最好。JQuery/JavaScript:遍歷表單域,執行計算,然後提交
摘要:我有十個表單域,每個域都有一個用戶可能提供或可能不提供的十進制小數值。當用戶點擊提交時,它應該在輸入字段中添加一個值,並在當前HTML頁面上顯示一個值,然後插入到數據庫中。
首先,我從表單輸入字段獲取該值並將其轉換爲帶有兩位小數的數字。然後我從HTML獲取當前總數,並將這兩個數字相加。之後,我將這些數據注入表單輸入字段,以便將其存儲在$_POST
中並插入到數據庫中。
如何讓我的代碼更加乾爽(即不要重複自己)?下面是兩個例子,但它們是完全除外元話費相同:
var subtotal = Number($("#housing").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-housing').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#housing').val(total);
var subtotal = Number($("#utilities").val());
subtotal = (subtotal).toFixed(2);
var currentTotal = $('#output-utilities').html().replace("$", "");
var total = Number(subtotal) + Number(currentTotal);
$('#utilities').val(total);
我想通過像這樣我的輸入字段進行迭代,但我試圖找出我怎麼能顯示邏輯內:
var input = $('.form-expenses :input');
input.each(function() {
// Insert switch statement here?? Some other construct??
});
HTML:(使用自舉3類)
FORM:
<form class="form-expenses form-horizontal" role="form" method="post" action="/profile/update">
<div class="form-group">
<label for="housing" class="control-label col-sm-3">Housing</label>
<div class="input-group input-group-lg col-sm-9">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="housing" id="housing" />
</div>
</div>
<div class="form-group">
<label for="utilities" class="control-label col-sm-3">Utilities</label>
<div class="input-group input-group-lg col-sm-9">
<span class="input-group-addon">$</span>
<input type="text" class="form-control" name="utilities" id="utilities" />
</div>
</div>
...
<button class="btn btn-lg btn-primary btn-block" id="update-expenses" type="submit"> Update</button>
</form>
OUTPUT:
<tr>
<td>Housing</td>
<td id="output-housing">$<?php echo $total['housing']?></td>
</tr>
<tr>
<td>Utilities</td>
<td id="output-utilities">$<?php echo $total['utilities']?></td>
</tr>
什麼是我們正在使用的相關HTML? –
@DavidThomas我會加上。 – Keven