我无法理解为什么这个简单的函数不能按照我希望的方式工作:)
c = document.form.product_catid.selectedIndex;
if (document.form.product_name.value == "" && document.form.product_catid[c].value == "")
{
alert ("Please, define at least product name or product category !");
return false;
}
else if (!(document.form.product_name.value == ""))
{
return true;
}
else if (!(document.form.product_catid[c].value == ""))
{
return true;
}
else
{
alert ("Please, dont define two of them at the same time!");
return false;
}
return true;
所有我想要的是当输入名称product_name被填充或选择名称product_catid被选中时,该函数返回true,但如果它们都没有定义,我希望它提醒两个不同的警报)谢谢大家为了帮助,我真的很感激!
答案 0 :(得分:2)
尝试使用Chrome开发者工具,Firebug或类似方法调试您的案例。我怀疑您是在尝试比较""
子句中的undefined
和document.form.product_catid[c].value == ""
(selectedIndex
为-1
时就是这种情况)。只需尝试!document.form.product_catid[c].value
。
答案 1 :(得分:1)
使用return
语句后,函数“结束”:
alert ("Please, define at least product name or product category !");
return false; // Exit point
...
...
// this will not be executed.
alert ("Please, dont define two of them at the same time!");
return false;
var returnValue = true;
if (document.form.product_name.value == "" && document.form.product_catid[c].value == "")
{
alert ("Please, define at least product name or product category !");
returnValue = false;
}
else if (document.form.product_name.value == "")
{
return true;
}
else if (document.form.product_catid[c].value == "")
{
return true;
}
else
{
alert ("Please, dont define two of them at the same time!");
returnValue = false;
}
return returnValue;
答案 2 :(得分:0)
试试这个:
var product = document.form.product_name.value;
var category = document.form.product_catid[document.form.product_catid.selectedIndex].value
if (product || category) {
if (product && category) {
alert ("Please, dont define two of them at the same time!");
return false;
}
else return true;
}
else {
alert ("Please, define at least product name or product category !");
return false;
}
答案 3 :(得分:0)
您的条件排序不正确。
目前的情况:
else
条件)考虑这一点:条件1确保两个输入都不为空 - 这意味着,逻辑上,其中至少有一个是非空的。接下来,鉴于我们现在知道其中至少有一个非空,条件2或条件3 将始终评估为true
。结果是第4个代码路径永远不会执行。
要解决此问题,请检查两个输入是否都未作为显式条件填充。
function validateInput() {
//replace values here to test function
var productCatId = "",
productName = "gjghj";
//uncomment when using real values
//var productCatId = document.form.product_catid[document.form.product_catid.selectedIndex].value,
// productName = document.form.product_name.value;
//check both aren't empty
if (productName == "" && productCatId == "")
{
alert ("Please, define at least product name or product category !");
return false;
}
//check both aren't populated
else if (productName != "" && productCatId != "")
{
alert ("Please, dont define two of them at the same time!");
return false;
}
//by now we know that both aren't empty, and both aren't populated, therefore only one is populated, so return true;
return true;
}