簡體   English   中英

通過使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM