我嘗試自動計算 html 輸入值以顯示輸入中的總值。這是我的輸入表單
<div class="col-sm-4">
<form>
<div class="mb-3">
<label for="">Price</label>
<input type="text" id="price" required class="price form-control">
</div>
<div class="mb-3">
<label for="">Amount</label>
<input type="text" id="amount" required class="amount form-control">
</div>
<div class="mb-3">
<label for="">Total</label>
<input type="text" id="total" required class="total form-control">
</div>
<button type="submit" class="btn btn-primary marketbuy">Buy </button>
</form>
</div>
在輸入表單中輸入金額值和價格值時,我想要自動總值。例子
price is 3
amount is 5
total is 15
當我輸入 3 和 5 時,總輸入自動顯示 15
var p1 = $('#price').val();
var p2 = $('#amount').val();
$('#total').val(p1*p2);
console.log()
此代碼不直接顯示在總輸入中,而是在重新加載時顯示。
jquery如何獲取。
uj5u.com熱心網友回復:
問題是因為您的代碼僅在頁面加載時運行。您需要將事件處理程式掛鉤到input
欄位,以便在用戶輸入值時也會計算總數。
以下是如何執行此操作的作業示例。請注意,更新total
欄位的通用邏輯被提取到其自己的函式中,該函式在頁面加載時以及在更新欄位時呼叫。另請注意,我將required
屬性添加到total
欄位中,以便用戶無法更新它 - 它只能以編程方式設定。
let $price = $('#price');
let $amount = $('#amount');
let updateTotal = () => $('#total').val($price.val() * $amount.val());
updateTotal(); // on page load
$('form input').on('input', updateTotal); // on value change
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-sm-4">
<form>
<div class="mb-3">
<label for="">Price</label>
<input type="text" id="price" required class="price form-control" />
</div>
<div class="mb-3">
<label for="">Amount</label>
<input type="text" id="amount" required class="amount form-control" />
</div>
<div class="mb-3">
<label for="">Total</label>
<input type="text" id="total" required class="total form-control" readonly />
</div>
<button type="submit" class="btn btn-primary marketbuy">Buy</button>
</form>
</div>
uj5u.com熱心網友回復:
$('form input').on('keyup',function(){
$('#total').val(parseInt($('#price').val()*$('#amount').val()));
});
<!-- The issue is because your code is only running when the page loads. You need to hook keyup event handlers to the input fields so that the total also gets calculated as the user enters values.-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-sm-4">
<form>
<div class="mb-3">
<label for="">Price</label>
<input type="text" id="price" required class="price form-control" />
</div>
<div class="mb-3">
<label for="">Amount</label>
<input type="text" id="amount" required class="amount form-control" />
</div>
<div class="mb-3">
<label for="">Total</label>
<input type="text" id="total" required class="total form-control" readonly />
</div>
<button type="submit" class="btn btn-primary marketbuy">Buy</button>
</form>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/504993.html
上一篇:所選選項(HTML下拉串列)未保存到localStorage
下一篇:卡沒有正確滾動堆疊