我想在我的网站上添加高度和宽度计算器,要求用户输入宽度和高度尺寸。但是应该验证最小值,如200和最大值,如5000和高度和宽度。
如果使用添加小于200且大于5000,则应提醒消息进行更正。
我已经开发了这个代码,但是它的工作并不像是单独询问
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
if(myBox1 >= 200 && myBox2 >=200) {
var result = document.getElementById('result');
var myResult = [(myBox1 * myBox2 * 0.69)/100];
result.value = parseFloat(myResult).toFixed(2);
} else {
alert("Please enter Minimum Width and Height is greater than 200")
}
}

<script type="text/javascript">
</script>
<div style="background-color:gray; border-bottom-width:2; border-color:orange;">
<h3 class="page-header">Price Calculator </h3>
<div class="docs-data">
<form name="pricecalculator" id="pricecalculator" method="post" action="<?php echo $buy;?>"/>
<div class="input-group" style="display:table-row-group; alert">
<label class="input-group-addon" for="dataWidth">Width</label>
<input id="box1" type="text" onchange="calculate();"/>
<!-- <input type="text" class="form-control" id="dataWidth" placeholder="width"> -->
<span class="input-group-addon">cm</span>
</div>
<div class="input-group">
<label class="input-group-addon" for="dataHeight">Height</label>
<input id="box2" type="text" onchange="calculate();"/>
<!-- <input type="text" class="form-control" id="dataHeight" placeholder="height"> -->
<span class="input-group-addon">cm</span>
</div>
<div class="input-group">
<label class="input-group-addon" for="dataHeight">Total Price</label>
<input id="result" type="text" readonly="readonly" onchange="calculate();"/>
<!--<input type="text" class="form-control" id="dataHeight" placeholder="height"> -->
<span class="input-group-addon">AUD</span>
</div>
</div>
</div>
&#13;
答案 0 :(得分:1)
试试这个:
function calculate() {
var myBox1 = document.getElementById('box1').value;
var myBox2 = document.getElementById('box2').value;
if (showAlert(myBox1, 'Width') && showAlert(myBox2, 'Height')) {
var result = document.getElementById('result');
var myResult = [(myBox1 * myBox2 * 0.69)/100];
result.value = parseFloat(myResult).toFixed(2);
}
}
function showAlert(boxValue, type) {
if(boxValue < 200) {
alert("Please enter Minimum " + type + " greater than 200");
return false;
}
return true;
}
答案 1 :(得分:-1)
当input-element失去焦点时,事件change
将触发。
我会使用以下决定:
function startValidator(){
var oldWidth = document.getElementById('box1').value;
var oldHeight = document.getElementById('box2').value;
setInterval(function(){
var newWidth = document.getElementById('box1').value;
var newHeight = document.getElementById('box2').value;
if (newWidth!=oldWidth || newHeight!=oldHeight){
calculate();
oldWidth = newWidth;
oldHeight = newHeight;
}
},400);
}