0

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.

2
  • Put your code up in the question as some of the users can't access external services such as jsfiddle. Commented Feb 19, 2016 at 5:55
  • You might want to include the code in the question rather than a link to jsfiddle, it's much more useful for other users. See meta.stackexchange.com/questions/149890/… Commented Feb 19, 2016 at 5:56

1 Answer 1

2

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

Fiddle here

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, But it possible if I want to get value from value="200" code it will be like var totals = parseInt($("input=[value]").val()); right?
Yes..But if it is the unique element then go with the id..$(#ID_SELECTOR).val()
Oh, Thank you so much, :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.