我有一个html页面,该页面具有供用户输入水果数量的输入字段。假设在按/向上键时,调用javascript文件方法并检查它是否为数字。如果不是数字,则将清除文本框字段。但是,当我尝试输入非数值时,不会清除我的文本框。我的代码中缺少什么吗?
HTML
<div class="form-group ">
<label class="control-label " for="name"> Name </label>
<input class="form-control" id="name" name="name" type="text" /> <span class="help-block" id="hint_name"> Enter your name </span>
</div>
<div class="form-group ">
<label class="control-label" for="apple"> Apple ( 69cents ) </label>
<input class="form-control form-control-input" id="apple" name="apple" type="text" autocomplete="off" onkeyup="isNumber(this,event)" /> <span class="help-block" id="hint_number"> Enter Qty </span>
</div>
<div class="form-group ">
<label class="control-label" for="orange"> Orange ( 59cents ) </label>
<input class="form-control form-control-input" id="orange" name="orange" type="text" autocomplete="off" onkeyup="isNumber(this,event)" /> <span class="help-block" id="hint_number1"> Enter Qty </span>
</div>
<div class="form-group ">
<label class="control-label" for="banana"> Banana ( 39cents ) </label>
<input class="form-control form-control-input" id="banana" name="banana" type="text" autocomplete="off" onkeyup="isNumber(this,event)" /> <span class="help-block" id="hint_number2"> Enter Qty </span>
</div>
Java脚本
function isNumber(idValue, evt) {
evt = (evt) ? evt : window.event;
var sum = 0;
var costOfApple = 0;
var costOfOrange = 0;
var costOfBanana = 0;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
document.getElementById('idValue.id').value = "";
document.getElementById('totalCost').value = "NaN";
$("#invalid-alert").fadeTo(2000, 500).slideUp(500, function() {
$("#invalid-alert").slideUp(500);
});
} else {
costOfApple = document.getElementById('apple').value * 69;
costOfOrange = document.getElementById('orange').value * 59;
costOfBanana = document.getElementById('banana').value * 39;
sum = (Number(costOfApple) + Number(costOfOrange) + Number(costOfBanana)) / 100;
document.getElementById('totalCost').value = "$" + (sum).toFixed(2);
}
}
最佳答案
问题陈述是
document.getElementById('idValue.id').value = "";
您正在将字符串'idValue.id'传递给该函数,且ID为ID的元素不存在,因此代码无法正常工作,并且您在浏览器控制台中一定会出错。
由于
idValue
是指调用事件处理程序的元素。您可以直接使用它来设置其属性。idValue.value = ""