我想通過小計和運輸成本的值顯示總價,但是我的代碼無法在輸入文本字段中獲得小計值。用jquery通過無線電改變輸入文本字段值
例子:
Subtotal: 200
Shipping A: 100 (checked)
Shipping B: 200
Totalprice: 300
or
Subtotal: 200
Shipping A: 100
Shipping B: 200 (checked)
Totalprice: 400
這裏是我的jsfiddle代碼。
我想通過小計和運輸成本的值顯示總價,但是我的代碼無法在輸入文本字段中獲得小計值。用jquery通過無線電改變輸入文本字段值
例子:
Subtotal: 200
Shipping A: 100 (checked)
Shipping B: 200
Totalprice: 300
or
Subtotal: 200
Shipping A: 100
Shipping B: 200 (checked)
Totalprice: 400
這裏是我的jsfiddle代碼。
使用
.val()
設定值不.html()
還要注意,$(".subtotal")
將返回jQuery
包裝的對象,但我們需要一個元素的值,因此使用parseInt($(".subtotal").val())
來獲取輸入字段的解析值。使用.text()
代替.html()
如果你希望得到text
值超過html
試試這個:
function updateCosts() {
var totals = parseInt($(".subtotal").val());
$.each($('#content input[type=radio]:checked'), function() {
totals += parseInt($.trim($(this).next('.shippingcost').text()));
});
$('#totalPrice').val(totals);
}
$(document).ready(function() {
$('#content input[type=radio]').change(updateCosts);
//_____________________________^^^^^^^_^^^^^^^^^^^
//Use change event instead of click, handler can be attached this way
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Subtotal:
<input type="text" value="200" name="subtotal" class="subtotal">
<div id="content">
A:
<input type="radio" name="shippingcost" checked> <span class="shippingcost"> 100 </span> B:
<input type="radio" name="shippingcost"> <span class="shippingcost"> 200 </span>
</div>
Total price:
<input type="text" name="totalprice" id="totalPrice">
非常感謝,但如果我想從價值中獲得價值=「200」代碼,它會像'var totals = parseInt($(「input = [value]」).val());'right? –
是的。但是,如果它是獨特的元素,那麼去與ID ..' $(#ID_SELECTOR).val()' – Rayon
哦,非常感謝,:) –
的問題把你的代碼改寫爲某些用戶無法訪問jsfiddle等外部服務。 –
您可能希望將代碼包含在問題中而不是指向jsfiddle的鏈接,對其他用戶更有用。見http://meta.stackexchange.com/questions/149890/prevent-posts-with-links-to-jsfiddle-and-no-code – akiraspeirs