我写了一个javascript来验证表单上的一些简单字段。我的问题是,即使表单上没有错误,代码也能正常工作。
具体而言,它会在if(openHour > closeHour)
这是代码
function checkForm()
{
var openHour;
var closeHour;
var i;
for(i=1;i<8;i++)
{
openHour = document.getElementById("openHours" + i).value;
closeHour= document.getElementById("closeHours" + i).value;
if(openHour > closeHour)
{
document.getElementById('error').innerHTML= "Opening Error at " + i;
return false;
}
if(openHour == "0" && closeHour > 0)
{
document.getElementById('error').innerHTML= "Closing Error at " + i;
return false;
}
}
}
答案 0 :(得分:2)
openHours和closeHours字段中是否始终有默认值?
尝试设置一些默认值,例如:
var openHour = 0;
var closeHour = 0;
然后在分配之前检查openHours和closedHours是否包含值:
if (document.getElementById("openHours" + i).value != null && document.getElementById("openHours" + i).value != "")
openHour = document.getElementById("openHours" + i).value;
if (document.getElementById("closeHours" + i).value != null && document.getElementById("closeHours" + i).value != "")
closeHour = document.getElementById("closeHours" + i).value;
答案 1 :(得分:1)
openHour = parseInt(document.getElementById("openHours" + i).value);
closeHour = parseInt(document.getElementById("closeHours" + i).value);
我只需要将值解析为整数,以便能够比较它们。
感谢大家的帮助