我有两个隐藏的输入HTML,我想与javascript onclick提交按钮进行比较。但即使看起来简单明了,它也不会起作用。
功能是:
function check() {
if ((parseFloat(document.getElementById("price_sell").value) < (parseFloat(document.getElementById("price").value)*0.95)) OR (parseFloat(document.getElementById("price_sell").value) > (parseFloat(document.getElementById("price").value)*1.05)) ){
alert("too high/low!");
}
}
输入文字如下:
<input type="hidden" id="price" name="price" value="<?php echo $prc ?>" />
<input type="hidden" id="price_sell" name="price_sell" />
我已检查隐藏的输入值,即使是&#39; price_sell&#39;是&#39;价格的两倍大/小,警报不会被激发。这有什么问题?
答案 0 :(得分:0)
将运算符OR更改为||。 这段代码,如果是JS代码,由于语法错误而无法正常工作。
答案 1 :(得分:0)
使用数字(变量)将文本转换为数字,然后进行比较数学。
实施例: -
var price = Number(document.getElementById(price).value);
var price_sell = Number(document.getElementById(price_sell).value);
var compare = price_sell - price;
或者您可以使用typeof
检查变量类型如果值为null
或undefined
,则数字函数会将其转换为0(零)。
即使'price_sell'是'price'的两倍大/小 -
/*
Errors - price = '10 $'; means remove currency symbols
or characters from price_sell and price variable
Use trim() to remove whitespace.
I recheck my code, and found brackets missing, and posted again.
*/
price_sell = Number(price_sell.trim());
price = Number(price.trim());
if ((price_sell > (price/0.80)) && (price_sell < (price*1.30))) {
// good
} else {
// bad
}
此致
答案 2 :(得分:0)
首先,@ Rakesh_Kumar将设置值提到price_sell
输入字段,然后尝试下面的代码。
function check() {
var price_sell = parseFloat(document.getElementById("price_sell").value);
var price = parseFloat(document.getElementById("price").value);
if ( (price_sell < ( price *0.95 ) ) || (price_sell > (price*1.05) ) ) {
alert("too high/low!");
}
}
在JS变量中存储price_sell
和price
值以获得更好的阅读目的。仅供参考,由于缺少括号和OR
的使用而导致语法错误,我已将其替换为||
。
答案 3 :(得分:0)
您必须通过||更改OR并为price_sell
添加一个值
使用此示例进行测试:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link href="estilos/estilos.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>Test</title>
<script type="text/javascript">
function check() {
var price_sell = parseFloat(document.getElementById("price_sell").value);
var price = parseFloat(document.getElementById("price").value);
if ((price_sell < (price * 0.95)) || (price_sell > (price * 1.05))) {
alert("too high/low!");
}
}
</script>
</head>
<body>
<input type="hidden" id="price" name="price" value="2" />
<input type="hidden" id="price_sell" name="price_sell" value="4"/>
<input type="button"
onclick="check()"
value="Check">
</body>
</html>