尝试在更改时更新变量时出现未定义的错误

时间:2018-01-31 20:35:27

标签: javascript

我有一些工作得很好的代码。但是,现在我试图使每次用户从选择字段中选择不同的选项时重新计算pricecalc。现在我在控制台中收到一个未定义的错误。

    function pricecalc() {
      var a = document.getElementById("field_0");
      var quantity = a.value.substring(0, 1);
      var b = document.getElementById("field_1");
      var type = b.value;
    
      if (quantity == '2') {
        var rate = '120';
      } else if (quantity == '3') {
        var rate = '110';
      } else {
        var rate = '100';
      }
    
      var price = rate * quantity;
    
      if (type == 'Credit card') {
        var price = price * 1.034;
      }
    
      var price_each = (price / quantity);
      var redirect = 'https://www.paypal.me/' + price;
    
      document.getElementById("cost").innerHTML = '£' + price;
      document.getElementById("costeach").innerHTML = '£' + price_each;
    }
This is the HTML

    <select name='field_0' id='field_0' class='text_select' onchange="pricecalc()">
      <option value="2 people">2 people</option>
      <option value="3 people">3 people</option>
      <option value="4 people">4 people</option>
      <option value="5 people">5 people</option>
      <option value="6 people">6 people</option>
    </select>
    
    <select name='field_1' id='field_1' class='text_select' onchange="pricecalc()">
      <option value="Bank transfer">Bank transfer</option>
      <option value="Debit card">Debit card</option>
      <option value="Credit card">Credit card</option>
    </select>
    
    <h4>
    <b>Total Price</b>
    <span id="cost">Hello World!</span>
    <b>Price Each</b>
    <span id="costeach">Hello World!</span>
    </h4>

我很确定这只是我把它放在函数中的一个问题,因为在函数之外它工作正常。任何人都可以帮助我理解为什么我将其置于更新选择选择时更新的函数的方法失败了?

以下是试用它的链接:https://jsfiddle.net/spadez/gwoss8L1/2/

1 个答案:

答案 0 :(得分:4)

它是一个jsfiddle配置的东西。

在js菜单中更改&#34;加载类型&#34;于:
No wrap - in <body>&#34;

设置为onLoad所以我猜这个功能还没有创建。

enter image description here