![](/img/trans.png)
[英]Save value of hidden field and radio input value when a radio button is checked using jQuery
[英]Change input text field value by radio checked using 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">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.