Javascript工资计算器

时间:2017-04-06 21:33:29

标签: javascript

我正在尝试使用Javascript制作年薪计算器。以下是我到目前为止的情况:



<div id="fulldiv">
		<p> Enter the following information to calculate your annual salary.</p>
					
		<p>Hourly Wage:
		<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
					
		<p>Hours Per Week:
		<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
		
		<button value="calculate" onclick="calcSalary()">Calculate</button></p>
		
		<p id="results"></p>
					
		<script type="text/javascript">
		
		function calcSalary() {
		var wage_element = document.getElementById('txt_wage');
		var wage = parseInt(wage_element.value);
		var hours_element = document.getElementById('txt_hours');
		var hours = parseInt(hours_element.value);
		var calculate = wage_element * hours_element * 52;
		document.getElementByID('results').innerHTML = calculate;
		}
		</script>
				
					
				

</div>
&#13;
&#13;
&#13;

当我点击按钮时,没有任何反应。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您的代码需要调整

var calculate = wage_element * hours_element * 52;

应改为

var calculate = wage * hours * 52;

答案 1 :(得分:1)

问题是你在计算元素而不是值。

@Gerard一分钟打败了我,但这是工作代码。

<div id="fulldiv">
		<p> Enter the following information to calculate your annual salary.</p>
					
		<p>Hourly Wage:
		<input type="text" name="wage" id="txt_wage" value ="0.00"/></p>
					
		<p>Hours Per Week:
		<input type="text" name="hours" id="txt_hours" value= "0.0"/> <br/><br/>
		
		<button value="calculate" onclick="calcSalary()">Calculate</button></p>
		
		<p id="results"></p>
					
		<script type="text/javascript">
		
		function calcSalary() {
      var wage_element = document.getElementById('txt_wage');
      var wage = parseInt(wage_element.value);
      var hours_element = document.getElementById('txt_hours');
      var hours = parseInt(hours_element.value);
      
      var calculate = wage * hours * 52;
      document.getElementById('results').innerHTML = calculate;
		}
		</script>
				
					
				

</div>

答案 2 :(得分:1)

那里有一些错别字。我稍微重写并简化了代码,以确保a)您的计算是关于输入的值和b)您使用标签来提供相对于输入的文本 - 而不是p。

function calcSalary() {
 var wage = parseFloat(document.getElementById('txt_wage').value);
 var hours = parseFloat(document.getElementById('txt_hours').value);
 var calculate = wage * hours * 52;
 
 document.getElementById('results').innerHTML = calculate;
}
<div id="fulldiv">
 <p> Enter the following information to calculate your annual salary.</p>
 <label for="txt_wage">Hourly Wage:</label>
 <input type="text" name="wage" id="txt_wage" value ="0.00"/>
					
 <label for="txt_hours">Hours Per Week:</label>
 <input type="text" name="hours" id="txt_hours" value= "0.0"/>   
  <br/><br/>
 <button value="calculate" onclick="calcSalary()">Calculate</button>
 <p id="results"></p>
</div>