入门级简单里程计算器:无法返回Var

问题描述 投票:1回答:1

我一直在尝试自我教育,并查看有关如何使这个简单的计算器与JS一起使用的其他工作。我已经通过google chrome对其进行了调试,但无法确定缺少的基本原理;

var theForm = document.forms["mmacalc"];

function getsjourn()
{
    var theForm = document.forms["mmacalc"];
    var sjourn = theForm.elements["sjourn"];
    var smile =0;
    if(sjourn.value!="")
    {
        smile = parseInt(sjourn.value);
    }
    
    return smile;
}

function getrjourn()
{
    var theForm = document.forms["mmacalc"];
    var rjourn = theForm.elements["rjourn"];
    var rmile =0;
    if(rjourn.value!="")
    {
        rmile = parseInt(rjourn.value);
    }
    
  return rmile;
}

function getmilalallow()
{
    var tmile = sjourn() * rjourn() ;
 
    document.getElementById('tjourn').innerHTML =
                                     "Your total mileage is"+tmile;
    var milal = sjourn() * rjourn() * 0.25 ;
 
     document.getElementById('mmac').innerHTML =
                                      "Your MMA Claim is: £"+milal;
                                       
}
<script type="javascript" src="formulacalculations.js"></script>
<form name="mmacalc" id="mmacalc" action="" method="post" target="_self">
    <label for ="sjourn"> Single Journey Mileage </label>
    <input type="text" id="sjourn" name="sjourn" value="" onclick="calculateTotal()">
    <br><hr>
    <label for ="rjourn"> Amount of Return Journeys </label>
    <input type="text" id="rjourn" name="rjourn" value="1" onclick="calculateTotal()">
    <br><hr>
    <input type="submit" value="Submit" onsubmit="getmilalallow()">
    <br><hr>
    <div class="tjourn" id="tjourn"></div>
    <div class="mmac" id="mmac"></div>
</form>
javascript html
1个回答
0
投票

为此使用表格是不明智的,因为当您单击input[type=submit]按钮时,它将发布数据并刷新页面。您可以使用event.preventDefault()解决此问题,但是没有必要。

我们将所有逻辑合并为一个功能,updateTotals,当单击按钮时,它将更新两段的innerHTML

function updateTotals() {
  var theForm = document.forms["mmacalc"],
      sjourn = document.getElementById('sjourn'),
      rjourn = document.getElementById('rjourn'),
      tjourn = document.getElementById('tjourn'),
      mmac = document.getElementById('mmac');
      
  console.log(sjourn.value, tjourn.value);
      
  let total = sjourn.value * rjourn.value;
  tjourn.innerHTML = `Your total mileage is ${total}`,
  mmac.innerHTML = `Your MMA Claim is ${total*0.25}`;
}
<div id="mmacalc">
  <label for="sjourn"> Single Journey Mileage </label>
  <input type="text" id="sjourn" name="sjourn" value="">
  <br>
  <hr>
  <label for="rjourn"> Amount of Return Journeys </label>
  <input type="text" id="rjourn" name="rjourn" value="1">
  <br>
  <hr>
  <button onclick="updateTotals()">Submit</button>
  <br>
  <hr>
  <div class="tjourn" id="tjourn"></div>
  <div class="mmac" id="mmac"></div>
  </form>
热门问题
推荐问题
最新问题