更新输入数字变量onclick

时间:2015-06-22 16:12:27

标签: javascript jquery html function

我正在尝试创建一个calculator样式的东西,你输入多少年的输入,你点击提交,它会在下面给你不同的结果而不重新加载页面。

我现在所有的计算都在工作,但是我无法在单击提交按钮时获取输入数字变量,然后在页面上打印正确的结果。 我一直在谷歌搜索一小时,我似乎无法把它弄好,我还在学习JS。

这是我的JS:

// Get Years
var years = (document.getElementById('years').value);
// Variables
var years;
var gallons = 1100 * 365;
var grain = 45 * 365;
var forest = 30 * 365;
var co2 = 20 * 365;
var animal = 1 * 365;
// Calculations
var gallonsTotal = years * gallons;
var grainTotal = years * grain;
var forestTotal = years * forest;
var co2Total = years * co2;
var animalTotal = years * animal;
// Functions
function calc() {
    var years = (document.getElementById('years').value);
    //Prints
    document.querySelector('.gallons').innerHTML = "Gallons " + gallonsTotal;
    document.querySelector('.grain').innerHTML = "Gains " + grainTotal;
    document.querySelector('.forest').innerHTML = "Forest " + forestTotal;
    document.querySelector('.co2').innerHTML = "Co2 " + co2Total;
    document.querySelector('.animals').innerHTML = "Animals " + animalTotal;
};

HTML:

<div class="small-4 columns">
    <input type="number" id="years" min="1" max="99">
</div>
<div class="small-8 columns">
    <a href="#" class="button postfix submit" onclick="calc()">Submit</a>
</div>

以下是我当前进展的一支笔:http://codepen.io/LukeD1uk/pen/BNwXMX

3 个答案:

答案 0 :(得分:2)

您在函数范围之外定义了所需的变量,解决方案是在render_to_string函数中定义它们: -

calc()

答案 1 :(得分:2)

您需要将所有计算放入 var store = { name:'corner store', address: '123 Main Street', products: [ 'string beans', 'coffee', 'milk' ] }; 函数:

calc()

Code Pen

答案 2 :(得分:0)

1)在函数内移动计算

2)在您的codepen中,考虑关闭<p class="gallons"><p>代码,而不是<p class="gallons"<p>

CodePen:http://codepen.io/anon/pen/VLMooV

// Variables
var gallons = 1100 * 365;
var grain = 45 * 365;
var forest = 30 * 365;
var co2 = 20 * 365;
var animal = 1 * 365;

// Functions
function calc(){
  // Calculations
  var gallonsTotal =  years * gallons;
  var grainTotal =  years * grain;
  var forestTotal =  years * forest;
  var co2Total =  years * co2;
  var animalTotal =  years * animal;

  var years = (document.getElementById('years').value);
  //Prints
  document.querySelector('.gallons').innerHTML = "Gallons " + gallonsTotal;
  document.querySelector('.grain').innerHTML = "Gains " + grainTotal;
  document.querySelector('.forest').innerHTML = "Forest " + forestTotal;
  document.querySelector('.co2').innerHTML = "Co2 " + co2Total;
  document.querySelector('.animals').innerHTML = "Animals " + animalTotal;
};