如何为两个输入添加自动计算

时间:2017-05-20 22:26:16

标签: javascript jquery html

我有这个计算器,我希望在用户添加输入后自动更新结果。 我尝试过.keyup的事情,但我不明白。 我对javascript很新。

这是我的项目代码。 http://codepen.io/Tristangre97/pen/zNvQON?editors=0010

HTML

<div class="card">
<div class="title">Input</div>
<br>

<div id="metalSpan"><input class="whiteinput" id="numMetal" type="number">
<div class="floater">Metal Quantity</div>

<div id="metalAlert">
</div>
</div>
<br>

<div id="forgeSpan"><input class="whiteinput" id="numForge" type=
"number">&nbsp;

<div class="floater">Forge Quantity</div></div>
<br>
<input checked id="rb1" name="fuel" type="radio" value="spark"> <label for=
"rb1">Sparkpowder</label> <input id="rb2" name="fuel" type="radio" value=
"wood"> <label for="rb2">Wood</label><br>
<br>
<button class="actionButton" id="submit" type="button">Calculate</button></div>

<div id="forgeAlert">
</div>

<div id="radioSpan">
<div class="floater">
</div>

<div class="card">
<div class="title2">Results</div>
<br>

<div id="result"><span id="spreadMetal"></span> metal <span class=
"plural"></span> forge<br>
<span id="spreadSpark"></span> <span id="fuelType"></span> <span class=
"plural"></span> forge <span id="allSpark"></span><br>
Completion Time: <span id="timeSpark"></span> minutes<br></div>
</div>
</div>

JS

var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
    $("#result").hide();
    $("#alert").hide();
    $("#submit").click(function() {
        metals = $("#numMetal").val();
        forges = $("#numForge").val();
        if (metals == 0 || metals == '') {
            $("#metalAlert").html("Please enter a value");
        }
        else if (forges == 0 || forges == '') {
            $("#metalAlert").html('');
            $("#forgeAlert").html("Please enter a value");
        }
        else {
            if ($("input[name=fuel]:checked").val() == "wood") {
                isWood = true;
            }
            else {
                isWood = false;
            }
            if (forges > 1) {
                $(".plural").html("per");
            }
            else {
                $(".plural").html("in the");
            }
            $("#forgeAlert").html('');
            if (metals % 2 == 0) {}
            else {
                metals = metals - 1;
                $("#alert").show();
            }
            ingots = metals / 2;
            spread = Math.floor(metals / forges);
            sparks = Math.ceil(((spread / 2) * 20) / 60);
            if (isWood) {
                sparks = sparks * 2;
            }
            tSpark = sparks * forges;
            if (forges > 1) {
                $("#allSpark").html(String("(" + tSpark + " total)"));
            }
            else {
                $("#allSpark").html(String(''));
            }
            $("#timeSpark").html(String((isWood) ? (sparks / 2) : sparks));
            $("#spreadMetal").html(String(spread));
            $("#spreadSpark").html(String(sparks));
            $("#fuelType").html((isWood) ? "wood" : "sparkpowder");
            $("#result").show();
        }
    });
});

4 个答案:

答案 0 :(得分:0)

看,你有两个选择:

将你提交的所有提交点击算法放入一个函数并将其调用为两个绑定:提交点击和输入更改(打开('更改'))或者只需删除计算按钮并将计算依赖于输入的onchange:每次更改检查或输入都会触发金属计算。第二种方法对我来说更有趣,并消除了用户点击计算的必要性(他已经点击了输入和检查)。显然你可以添加一个过滤器,只允许在一定数量的最小数据填充后运行计算功能,最好避免因缺少数据而导致的不良结果。

答案 1 :(得分:0)

要在现场输入内容时运行该功能,请尝试

$("input").on('input', function() { .. });

var metals = 0;
var ingots = 0;
var forges = 0;
var spread = 0;
var sparks = 0;
var tSpark = 0;
var isWood = false;
$(document).ready(function() {
  $("#result").hide();
  $("#alert").hide();
  $("input").on('input', function() {
    metals = $("#numMetal").val();
    forges = $("#numForge").val();
    if (metals == 0 || metals == "") {
      $("#metalAlert").html("Please enter a value");
    } else if (forges == 0 || forges == "") {
      $("#metalAlert").html("");
      $("#forgeAlert").html("Please enter a value");
    } else {
      if ($("input[name=fuel]:checked").val() == "wood") {
        isWood = true;
      } else {
        isWood = false;
      }
      if (forges > 1) {
        $(".plural").html("per");
      } else {
        $(".plural").html("in the");
      }
      $("#forgeAlert").html("");
      if (metals % 2 == 0) {
      } else {
        metals = metals - 1;
        $("#alert").show();
      }
      ingots = metals / 2;
      spread = Math.floor(metals / forges);
      sparks = Math.ceil(spread / 2 * 20 / 60);
      if (isWood) {
        sparks = sparks * 2;
      }
      tSpark = sparks * forges;
      if (forges > 1) {
        $("#allSpark").html(String("(" + tSpark + " total)"));
      } else {
        $("#allSpark").html(String(""));
      }
      $("#timeSpark").html(String(isWood ? sparks / 2 : sparks));
      $("#spreadMetal").html(String(spread));
      $("#spreadSpark").html(String(sparks));
      $("#fuelType").html(isWood ? "wood" : "sparkpowder");
      $("#result").show();
    }
  });
});
body {
  background-color:#316b6f;
  font-family:Helvetica,sans-serif;
  font-size:16px;
}
	.whiteinput {
	outline: none;
	border-width: 0px;
	margin: 0;
	padding: .5em .6em;
	border-radius: 2px;
	font-size: 1em;
	color: #316b6f;
}
 .actionButton {
	background-color: #316B6F;
	color: #fff;
	padding: .5em .6em;
	border-radius: 3px;
	border-width: 0px;
	font-size: 1em;
	cursor: pointer;
	text-decoration: none;
     -webkit-transition: all 250ms;
  transition: all 250ms;
}
.actionButton:hover {
	color: #fff;
   
}
.actionButton:active {
	background: #BBFF77;
  color: #316B6F;
   -webkit-transition: all 550ms;
  transition: all 550ms;
}
.card {
  position: relative;
  background: #4E8083;
  color:#FFFFFF;
  border-radius:3px;
  padding:1.5em;
  margin-bottom: 3px;
}

.title {
  background: #76B167;
  padding: 3px;
  border-radius: 3px 0px 0px 0px;
  position: absolute;
  left: 0;
  top: 0;
  margin-bottom: 5px;
}

.title2 {
  background: #2F3A54;
  padding: 3px;
  border-radius: 3px 0px 0px 0px;
  position: absolute;
  left: 0;
  top: 0;
  margin-bottom: 5px;
}

.floater {
  padding: 3px;
}
.radiobtn {
  background: red;
  border-radius: 2px;
}
input[type=radio] + label:before {
    content: "";  
    display: inline-block;  
    width: 20px;  
    height: 20px;  
    vertical-align:middle;
    margin-right: 8px;  
    background-color: #aaa;  
   
  margin-bottom: 6px;
    border-radius: 2px;  
   -webkit-transition: all 450ms;
  transition: all 450ms;
}
input[type=radio], input[type=checkbox] {
    display:none;
}
input[type=radio]:checked + label:before {
    content: "\2022"; /* Bullet */
    color:white;
    background-color: #fff; 
    font-size:1.8em;
    text-align:center;
    line-height:14px;
    margin-right: 8px;  
}
input[type=checkbox]:checked + label:before {
    content:"\2714"; 
    color:white;
    background-color: #fff; 
    text-align:center;
    line-height:15px;
 
}
*:focus {
    outline: none;
}
 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>
<div class="card">
  <div class="title">Input</div><br>
		<div id="metalSpan">
				<input class="whiteinput" id="numMetal" type="number">
<div class="floater">
					Metal Quantity
				</div>
				<div id="metalAlert">
				</div>
			</div>
			<br>
			<div id="forgeSpan">
				<input class="whiteinput" id="numForge" type="number">&nbsp;
	<div class="floater">
					Forge Quantity
				</div>
				</div>
				<br>
  <input type="radio" id="rb1" name="fuel" value="spark" checked>
<label for="rb1">Sparkpowder</label>
  
<input type="radio" id="rb2" name="fuel" value="wood">
<label for="rb2">Wood</label><br><br>
  
  
  	<button class="actionButton" id="submit"
			type="button">Calculate</button>
			</div>
		
		

			<div id="forgeAlert">
			</div>
			<div id="radioSpan">
				<div class="floater">
				</div>
        <div class="card">
          <div class="title2">Results</div><br>
				<div id="result">
					<span id="spreadMetal"></span> metal <span class="plural"></span> forge<br>
					<span id="spreadSpark"></span> <span id="fuelType"></span> <span class="plural"></span> forge <span id=
					"allSpark"></span><br>
					Completion Time: <span id="timeSpark"></span> minutes<br>
				</div>
			</div>
		</div>

Codepen

它会触发您的错误,因为这是您功能的一部分。

有关input method的更多信息。

答案 2 :(得分:0)

为了自动更新计算,我们必须听取用户对输入元素的输入。对现有代码进行最少更改的最简单方法是添加输入事件并在按钮上发出click

$("#numMetal, #numForge").on('input', function(){
  $("#submit").click()
})

更好的方法是将计算逻辑移动到单独的函数并在期望的事件上调用它:

$("#numMetal, #numForge").on('input', function(){
  calculate()
})
 $("#submit").click(function(){
  calculate()
 })

这将使代码保持结构化并更易于遵循。

答案 3 :(得分:0)

试试这个:

$( "#numMetal, #numForge" ).keyup(function(event) {
    console.log('a key has been pressed');
    // add code to handle inputs here
});

这里发生的事情是事件监听器 - 关键事件 - 绑定到页面上的两个输入。当发生这种情况时,将运行内部代码。

正如其他评论中所建议的那样,使用提交调用中的所有输入处理代码调用单独的方法是个好主意,这样可以避免代码重复。

您还需要将事件绑定到复选框。这可以通过以下方式实现:

$( "input[name=fuel]" ).on('change',function() {
    console.log('checkbox change');
    // call processing method here
});