我的Javascript代码无法解决错误

Cant work out bug with my Javascript code

本文关键字:解决 错误 Javascript 代码 我的      更新时间:2023-09-26

我无法将总价显示在屏幕上。我确信这只是一个小错误,但我找不到它。

var cabbage_prices = new Array();
cabbage_prices["Round6"]=20;
cabbage_prices["Round8"]=25;
cabbage_prices["Round10"]=35;
cabbage_prices["Round12"]=75;
var filling_prices= new Array();
filling_prices["None"]=0;
filling_prices["Lemon"]=5;
filling_prices["Custard"]=5;
filling_prices["Fudge"]=7;
filling_prices["Mocha"]=8;
filling_prices["Raspberry"]=10;
filling_prices["Pineapple"]=5;
filling_prices["Dobash"]=9;
filling_prices["Mint"]=5;
filling_prices["Cherry"]=5;
filling_prices["Apricot"]=8;
filling_prices["Buttercream"]=7;
filling_prices["Chocolate Mousse"]=12;
function getCabbageSizePrice()
{  
  var cabbageSizePrice=0;
  var theForm = document.forms["cabbageForm"];
  var selectedCabbage = theForm.elements["selectedcabbage"];
  for(var i = 0; i < selectedCabbage.length; i++)
  {
    if(selectedCabbage[i].checked)
    {
      cabbageSizePrice = cabbage_prices[selectedCabbage[i].value];
      break;
    }
  }
  return cabbageSizePrice;
}
function getFillingPrice()
{
  var cabbageFillingPrice=0;
  var theForm = document.forms["cabbageform"];
  var selectedFilling = theForm.elements["filling"];
  cabbageFillingPrice = filling_prices[selectedFilling.value];
  return cabbageFillingPrice;
}
function calculateTotal()
{
  var cabbagePrice = getCabbageSizePrice() + getFillingPrice();
  var divobj = document.getElementById('totalPrice');
  divobj.style.display='block';
  divobj.innerHTML = "Total Price For the Cabbage $"+cabbagePrice;
}
function hideTotal()
{
  var divobj = document.getElementById('totalPrice');
  divobj.style.display='none';
}
<div id="wrap">
  <form action="" id="cabbageform" onsubmit="return false;">
    <div>
      <div class="cont_order">
        <fieldset>
          <legend>Order Your Cabbages</legend>
          <label >Size of your Cabbage</label>
          <label class='radiolabel'><input type="radio"  name="selectedcabbage" value="Round6" onclick="calculateTotal()" />Round Cabbage 6" -  serves 3 people ($20)</label><br/>
          <label class='radiolabel'><input type="radio"  name="selectedcabbage" value="Round8" onclick="calculateTotal()" />Round Cabbage 8" - serves 5 people ($25)</label><br/>
          <label class='radiolabel'><input type="radio"  name="selectedcabbage" value="Round10" onclick="calculateTotal()" />Round Cabbage 10" - serves 10 people($35)</label><br/>
          <label class='radiolabel'><input type="radio"  name="selectedcabbage" value="Round12" onclick="calculateTotal()" />Round Cabbage 12" - serves 15 people($75)</label><br/>
          <br/>
          <label >Cabbage Filling</label>
          <select id="filling" name='filling' onchange="calculateTotal()">
            <option value="None">Select Filling</option>
            <option value="Lemon">Lemon Sauce($5)</option>
            <option value="Custard">Custard Sauce($5)</option>
            <option value="Fudge">Fudge Sauce($7)</option>
            <option value="Mocha">Mocha($8)</option>
            <option value="Raspberry">Raspberry($10)</option>
            <option value="Pineapple">Pineapple($5)</option>
            <option value="Dobash">Dobash($9)</option>
            <option value="Mint">Mint($5)</option>
            <option value="Cherry">Cherry($5)</option>
            <option value="Apricot">Apricot($8)</option>
            <option value="Buttercream">Buttercream($7)</option>
            <option value="Chocolate Mousse">Chocolate Mousse($12)</option>
          </select>
          <br/>            
        </fieldset>
      </div>
      <div class="cont_details">
        <fieldset>
          <legend>Contact Details</legend>
          <label for='name'>Name</label>
          <input type="text" id="name" name='name' />
          <br/>
          <label for='address'>Address</label>
          <input type="text" id="address" name='address' />
          <br/>
          <label for='phonenumber'>Phone Number</label>
          <input type="text"  id="phonenumber" name='phonenumber'/>
          <br/>
        </fieldset>
      </div>
      <input type='submit' id='submit' value='Submit' onclick="calculateTotal()" />
    </div>  
  </form>
</div>

  1. 您最好使用JQuery来操作页面元素。对象模型在不同的浏览器中是不同的。因此,JQuery脚本将是通用的并且易于编写。

  2. 您最好使用声明性样式来设置值(使用数据属性(。

  3. 您最好在脚本中订阅事件处理程序,而不是在HTML代码中。

我修复了你的代码。

  1. 我添加了<input type="text" id="total" name='total' readonly="readonly" />以提供计算结果。

  2. 我的代码调用了$(document).ready()事件。

这是$(document).ready():的缩短等价物

$(function() { // YOUR JQUERY CODE });

  1. 我订阅了两个变更活动:

$('#cabbageform input[name="selectedcabbage"]').change(...)

$('#cabbageform select[name="filling"]').change(...)

  1. 在hanlder中,我搜索了当前的形式以获得更通用的解决方案:var $form = $(this).closest('form');

  2. 我将此表单传递给我们的计算函数:updateTotal($form);

  3. updateTotal()中,我寻找选中的单选按钮和选择的选项,并从中获取价格:

$form.find('input[name="selectedcabbage"]:checked').data('price')

$form.find('select[name="filling"] option:selected').data('price')

data('price')方法返回data-price属性的值。

  1. 如果仅在其不是NaN(不是数字(的情况下使用该值,则意味着它是一个数字:

if (!isNaN(selectedcabbage))

  1. 我汇总价格并将其设置为总投入:

$form.find('input[name="total"]').val(total);

附言:如果有什么不清楚的地方,请随时提问。

function updateTotal($form)
{  
    var total = 0;
    var selectedcabbage = $form.find('input[name="selectedcabbage"]:checked').data('price');
    if (!isNaN(selectedcabbage))
    {
        total += selectedcabbage;
    }
    
    var filling = $form.find('select[name="filling"] option:selected').data('price');
    if (!isNaN(filling))
    {
        total += filling;
    }
    
    $form.find('input[name="total"]').val(total);
}
$(function() {
    $('#cabbageform input[name="selectedcabbage"]').change(function () {
        var $form = $(this).closest('form');
        updateTotal($form);
    });
    $('#cabbageform select[name="filling"]').change(function () {
        var $form = $(this).closest('form');
        updateTotal($form);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrap">
    <form action="" id="cabbageform">
    <div>
        <div class="cont_order">
           <fieldset>
            <legend>Order Your Cabbages</legend>
            <label >Size of your Cabbage</label>
            <label class='radiolabel'><input type="radio"  name="selectedcabbage" value="Round6" data-price="20" />Round Cabbage 6" -  serves 3 people ($20)</label><br/>
            <label class='radiolabel'><input type="radio"  name="selectedcabbage" value="Round8" data-price="25" />Round Cabbage 8" - serves 5 people ($25)</label><br/>
            <label class='radiolabel'><input type="radio"  name="selectedcabbage" value="Round10" data-price="35" />Round Cabbage 10" - serves 10 people($35)</label><br/>
            <label class='radiolabel'><input type="radio"  name="selectedcabbage" value="Round12" data-price="75" />Round Cabbage 12" - serves 15 people($75)</label><br/>
            <br/>
            <label >Cabbage Filling</label>
            <select id="filling" name='filling'>
            <option value="None">Select Filling</option>
            <option value="Lemon" data-price="5">Lemon Sauce($5)</option>
            <option value="Custard" data-price="5">Custard Sauce($5)</option>
            <option value="Fudge" data-price="7">Fudge Sauce($7)</option>
            <option value="Mocha" data-price="8">Mocha($8)</option>
            <option value="Raspberry" data-price="10">Raspberry($10)</option>
            <option value="Pineapple" data-price="5">Pineapple($5)</option>
            <option value="Dobash" data-price="9">Dobash($9)</option>
            <option value="Mint" data-price="5">Mint($5)</option>
            <option value="Cherry" data-price="5">Cherry($5)</option>
            <option value="Apricot" data-price="8">Apricot($8)</option>
            <option value="Buttercream" data-price="7">Buttercream($7)</option>
            <option value="Chocolate Mousse" data-price="12">Chocolate Mousse($12)</option>
           </select>
            <br/>            
            </fieldset>
        </div>
        <div class="cont_details">
            <fieldset>
            <legend>Contact Details</legend>
            <label for='name'>Name</label>
            <input type="text" id="name" name='name' />
            <br/>
            <label for='address'>Address</label>
            <input type="text" id="address" name='address' />
            <br/>
            <label for='phonenumber'>Phone Number</label>
            <input type="text"  id="phonenumber" name='phonenumber'/>
            <br/>
            <label for='total'>Total price</label>
            <input type="text"  id="total" name='total' readonly="readonly" />
            <br/>
            </fieldset>
        </div>
        <input type='submit' id='submit' value='Submit' />
    </div>  
   </form>
</div>