0

I would like to use 2 selects to change the value of the total price.

<span id="totalprice">$10</span>

<select id="upgrade1">
    <option value="10">A</option>
    <option value="20">B</option>
</select>
<select id="upgrade2">
    <option value="10">C</option>
    <option value="20">D</option>
</select>

So for example selecting B and D the total price would reflect $40.

This is my jQuery I have so far, but I do not know what goes into the addition part...

$('#upgrade1, #upgrade2').on('change', function() {
    $('#totalprice').text($(this).val());
});

How do I do the jQuery addition part?

Aaron Blenkush
  • 3,034
  • 2
  • 28
  • 54
Elijah Yang
  • 265
  • 1
  • 7
  • 16

3 Answers3

1

You were missing closing tags (</select>) on your dropdown elements. See the code below, and use this jsFiddle to see it in action. http://jsfiddle.net/3eVc6/

HTML:

<span id="totalprice">$10</span>

<select id="upgrade1">
    <option value="10">A</option>
    <option value="20">B</option>
</select>
<select id="upgrade2">
    <option value="10">C</option>
    <option value="20">D</option>
</select>

JavaScript (include jQuery library)

$('#upgrade1, #upgrade2').on('change', function () {
    sum = Number($('#upgrade1').val()) + Number($('#upgrade2').val());
    $('#totalprice').html('$' + sum);
});

Thanks to @Blazemonger for pointing out that parseInt(val) could possibly lead to parsing issues (since the radix is not specified). I've replaced it with Number()

Aaron Blenkush
  • 3,034
  • 2
  • 28
  • 54
  • [Always, always, always use a radix with parseInt.](http://stackoverflow.com/questions/850341/how-do-i-work-around-javascripts-parseint-octal-behavior) – Blazemonger Feb 28 '13 at 20:16
  • @Blazemonger: You're right. Number() would be a better option because it avoids the parsing issues, and can return a floating point number (which may be preferable in the OP's example, since he's dealing with price). – Aaron Blenkush Feb 28 '13 at 20:21
0

HTML:

Some small corrections - closing select statements

<span id="totalprice">30</span>

<select id="upgrade1">
    <option value="10">A</option>
    <option value="20">B</option>
</select>
<select id="upgrade2">
    <option value="10">C</option>
    <option value="20">D</option>
</select>

Javascript (jQuery):

Get the value of each required field, passing through parseInt to convert to number, and add them together

$('#upgrade1, #upgrade2').on('change', function() {
  $('#totalprice').text("$"+parseInt($('#upgrade1').val())+parseInt($('#upgrade2').val()));
});
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
0

You are very close already.

$('#upgrade1,#upgrade2').on('change', function() {
    $('#totalprice').text("$" + (parseInt($('#upgrade1').val(),10) +
                                 parseInt($('#upgrade2').val(),10)) );
});
Blazemonger
  • 90,923
  • 26
  • 142
  • 180
windywindy
  • 66
  • 2