[英]If statement executing both if and else
I'm building a web app that converts Galloons to Liters and vise versa.我正在构建一个 web 应用程序,它将加仑转换为升,反之亦然。 Got one textbox to enter gallon/litters, the user selects on a radio button what they want to convert too.有一个文本框来输入加仑/升,用户也可以在单选按钮上选择他们想要转换的内容。 Now the problem arises when validating the input: for liters it must be Greater than 0 but less than 1000 for the gallons it must be greater than 0 but less than 4000 .现在在验证输入时出现问题:对于升,它必须大于 0 但小于 1000 ,对于加仑,它必须大于 0 但小于 4000 。 So if I've selected liters it must validate only liters but both validations are coming up.因此,如果我选择了升,它必须只验证升,但两个验证都会出现。 Here's my code:这是我的代码:
Form :表格:
<body onload="setup()">
<div data-role="page">
<div style="padding: 20px;">
<div data-role="fieldcontain">
<input type="number" id="temperature" name="temperature">
<label id="label">Gallons</label>
</div>
<fieldset data-role="controlgroup">
<legend>Convert to:</legend>
<input type="radio" name="units" id="Gallons" value="Gallons"
onclick="setUnits('Liters')">
<label for="Gallons">Gallons</label>
<input type="radio" name="units" id="Liters" value="Liters"
checked="checked" onclick="setUnits('Gallons')">
<label for="Liters">Liters</label>
</fieldset>
<input type="button" onclick="convert()" value="Convert">
<p id="answer"></p>
</div>
</div>
</body>
JavaScript : JavaScript :
function setup()
{
var cType;
setUnits("Gallons");
cType = "Gallons";
document.getElementById("Gallons").onclick =
function () {
cType="";
cType="Liters";
setUnits("Liters");
CheckInput(cType);
};
document.getElementById("Liters").onclick =
function () {
cType="";
cType="Gallons";
setUnits("Gallons");
CheckInput(cType);
};
CheckInput(cType);
}
function setUnits(unit) {
var label = document.getElementById("label");
label.innerHTML = unit;
}
function CheckInput(cType) {
var CheckInputcType= cType;
var angleInput = document.getElementById("temperature");
if(CheckInputcType.localeCompare("Gallons")==0)
{
angleInput.addEventListener("blur",validateG);
}
else(CheckInputcType.localeCompare("Liters")==0)
{
angleInput.addEventListener("blur",validateL);
}
}
function validateL(){
var angleInput = document.getElementById("temperature");
if (angleInput.value >= 1000 || angleInput.value<=0)
{
alert('Liters must be between 0 and 1000');
angleInput.value = "";
}
}
function validateG() {
var angleInput = document.getElementById("temperature");
if (angleInput.value >= 4000 || angleInput.value<=0)
{
alert('Gallons must be between 0 and 4000');
angleInput.value = "";
}
}
You have a problem with your method CheckInput(cType), because every time you click on Galons or liters radio button you are adding a new listener event on temperature input.您的方法 CheckInput(cType) 有问题,因为每次单击 Galons 或 liters 单选按钮时,您都会在温度输入上添加一个新的侦听器事件。 Just simply create one listener and verify radio state on that validator method.只需简单地创建一个侦听器并在该验证器方法上验证无线电 state。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.