2012-11-27 30 views
-2
<script language="JavaScript"> 
    function validate(x) { 



     var cur_p = document.getElementById('current').value; 
     var new_p = document.getElementById('new').value; 
     var con_p = document.getElementById('confirm').value; 

     document.getElementById('msg_p').innerHTML = ''; 
     document.getElementById('msg_cur').innerHTML = ''; 


     if(x != cur_p) 
     { document.getElementById('msg_cur').innerHTML = ' Your password was incorrect'; 
      return false; 
     } 

     if(new_p != con_p) 
     { document.getElementById('msg_p').innerHTML = 'Passwords do not match'; 
      return false; 
     } 

     return (true); 

    } 
</script> 

HTMLJavaScript不能同时工作

<form action='change-password.php' method='post' onsubmit="return validate('<?=$current?>')" > 

我有这些对我的代码。 我无法同时显示这些ifs的结果。

if(x != cur_p) 
and 
if(new_p != con_p) 

如果我放置

if(x != cur_p){} 

if(new_p != con_p){} 

如果响应结果顶端(X!= cur_p)将显示,而后者不会

,反之亦然。

我该怎么让这两个IFS (假设这些条件都满足)

回答

2

首先,你有一个错字在你的代码

document.getElementById('msg_p').innerHTM = ''; <-- Missing an L 

二,当然,如果你回来,它退出功能。所以代码不会执行这两个语句。

变化

if(x != cur_p) 
    { document.getElementById('msg_cur').innerHTML = ' Your password was incorrect'; 
     return false; 
    } 

    if(new_p != con_p) 
    { document.getElementById('msg_p').innerHTML = 'Passwords do not match'; 
     return false; 
    } 

    return (true); 

var isValid = true; 
    if(x != cur_p) 
    { document.getElementById('msg_cur').innerHTML = ' Your password was incorrect'; 
     isValid = false; 
    } 

    if(new_p != con_p) 
    { document.getElementById('msg_p').innerHTML = 'Passwords do not match'; 
     isValid = false; 
    } 

    return isValid; 
+0

'HTM'中缺失的'L'不是我猜测的原因。 但你的第二个解决方案是伟大的。 非常感谢你@epascarello你节省了我的一天 –

3

的结果,问题是,你正在返回后的第一个false,所以第二个是从未达到。相反,在每个布尔变量中设置一个布尔变量并返回布尔变量(如果两个都失败,将为true,如果两个都失败,则返回false)。

// Boolean variable starts true, will get set to false if either condition is met: 
    var okFlag = true; 
    if(x != cur_p) 
    { document.getElementById('msg_cur').innerHTML = ' Your password was incorrect'; 
     // Set to false 
     okFlag = false; 
    } 

    if(new_p != con_p) 
    { document.getElementById('msg_p').innerHTML = 'Passwords do not match'; 
     // Set to false 
     okFlag = false; 
    } 
    // Return the flag, which is either true or false. 
    return okFlag; 
+1

+1理解的问题! – ahren