无法在将字符串转换为int时添加总值

时间:2017-08-31 20:08:22

标签: javascript html

我有两个选择字段,向用户询问两个不同的问题,并根据所选值将总值添加到最终总数中。我没有完全理解为什么当我首先选择第二个选择字段时,最终总数会说$ NaN USD,但如果我先选择第一个选择字段,那么它不会显示$ 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>
&#13;
&#13;
&#13;

我对Javascript相当新,所以任何帮助都会受到赞赏,因为我一直在处理这个问题。

1 个答案:

答案 0 :(得分:3)

你没有给出一个初始值,所以在顶部,使得总值为: div.standard ul{ display:list-item !Important; list-style-type: disc !Important; }

你没有反过来获得NaN的原因是因为你使用了var total = 0;,如果为null,它会给它一个默认值0。