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 .
Use
.val()
to set value not.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. Use .text()
instead of .html()
if you wish to get text
value than 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">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.