简体   繁体   English

通过使用jquery选中的单选更改输入文本字段值

[英]Change input text field value by radio checked using jquery

I want to display total price with sum by values of subtotal and shipping cost, But my code can't get subtotal value on input text field. 我想按小计和运输成本的值显示总价,但我的代码无法在输入文本字段中获得小计值。

Example : 范例:

Subtotal: 200
Shipping A: 100 (checked)
Shipping B: 200
Totalprice: 300

or

Subtotal: 200
Shipping A: 100 
Shipping B: 200 (checked)
Totalprice: 400

Here's my code on jsfiddle . 这是我在jsfiddle上的代码。

Use .val() to set value not .html() 使用.val()设置值,而不是.html()

Also note, $(".subtotal") will return jQuery wrapped object but we need value of that element hence Use parseInt($(".subtotal").val()) to get parsed value of that input field. 还要注意, $(".subtotal")将返回jQuery包装的对象,但是我们需要该元素的值,因此请使用parseInt($(".subtotal").val())来获取该输入字段的解析值。 Use .text() instead of .html() if you wish to get text value than html 如果您希望获取text值而不是html请使用.text()而不是.html()

Try this: 尝试这个:

 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"> 

Fiddle here 在这里摆弄

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM