0

I have two select fields that ask the user two different questions and adds the overall value to the final total depending on the selected value. I'm not fully understanding why the final total is saying $NaN USD when I select the second select field first but if I select the first select field first then it doesn't display $NaN USD.

var total;

$('.form-contro').on('change', function() {
  var get = $('#form-contro option:selected').val();
  total = Number(get);

  $('.text-center h2 span').html(total + " USD");
});


$('.form-contr').on('change', function() {
  var get = $('#form-contr option:selected').val();

  if (get === 'no') {
    total = 1000;
  } else if (get === 'yes') {
    total = total + 30;
  }

  $('.text-center h2 span').html(total + " USD");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="wrapper" style="margin-top: 20px; font-size: 12px; color: #888; font-family: 'Raleway', sans-serif;" for="states">Number of items:</label>
<select class="form-contro" id="form-contro" style="width: 320px; height: 40px; text-indent: 10px; display: block; margin: 0 auto; border-radius: 4px; border-style: solid; border-color: #343434;">
     <option value="90" id="items">1 Item</option>
     <option value="95.50" id="items">2 Items</option>
     <option value="100" id="items">3 Items</option>
     <option value="105" id="items">4 Item</option>
</select>

<label class="wrapper" style="margin-top: 20px; font-size: 12px; color: #888; font-family: 'Raleway', sans-serif;" for="states">Will you be flying?</label>
<select class="form-contr" id="form-contr" style="width: 320px; height: 40px; text-indent: 10px; display: block; margin: 0 auto; border-radius: 4px; border-style: solid; border-color: #343434;">
     <option value="no" id="items">No</option>
     <option value="yes" id="items">Yes</option>
</select>

<div class="text-center" style="clear: both;">
    <h2 style="margin-top: 40px;">Total amount $<span id="new_text">90 USD</span></h2>
</div>

I'm fairly new to Javascript so any help is appreciated since I've been working on this problem awhile.

1
  • My ultimate goal is to add the two select values together without getting the $NaN. Commented Aug 31, 2017 at 20:11

1 Answer 1

3

You didn't give total an initial value, so at the top, make the value of total: var total = 0;

The reason you don't get NaN the other way around, is because you used Number(get), which gives it a default value of 0 if null.

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

1 Comment

Wow, that was super easy.. Thanks!

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.