2017-08-01 71 views
1

我有一個登錄頁面,我添加了一個驗證,只要輸入爲空,您就無法登錄,我希望驗證消息在用戶輸入某些輸入時消失。我希望它很清楚。這裏是我的代碼:添加正確的值後,驗證消息不會消失

function Validation() { 
 

 

 
    var x = document.getElementById("username").value; 
 
    var y = document.getElementById("password").value; 
 

 

 
    if (x == "") { 
 

 
    document.getElementById("demo1").innerHTML = "*please write name"; 
 

 
    } else { 
 
    document.getElementById("demo1").innerHTML = ""; 
 
    } 
 

 
    if (y == "") { 
 

 

 
    document.getElementById("demo2").innerHTML = "*please write password"; 
 
    return false; 
 
    } else { 
 
    document.getElementById("demo2").innerHTML = ""; 
 
    } 
 
}
<div id="form-wrapper"> 
 

 
    <label for="username">UserName </label> 
 
    <input type="text" id="username" name="myuser" /><span class="validation" id="demo1"> </span> 
 
    <br/> <br/> 
 
    <label for="password"> Password </label> 
 
    <input type="password" id="password" name="mypassword" /> 
 
    <span class="validation" id="demo2"> </span> 
 
    <br /> 
 

 
    <input type="submit" id="login" value="Log in" onclick="return Validation()" /> <br /> 
 
    <input type="checkbox" checked="checked" /> Remember me 
 

 

 
</div>

+0

那是因爲你使用的是上的onClick功能實現它。您還應該在用戶名輸入的onChange上調用它。 – dev8080

+0

對不起,我不明白,所以我應該添加onChange到按鈕或輸入? – ghadah

+0

將其添加到輸入。兩個都 。 – dev8080

回答

2

您需要用戶開始在密碼或用戶名框中鍵入要儘快打電話給你Validation()功能。您可以通過onkeyup事件像

<input type="password" id="password" name="mypassword" onkeyup="Validation()" /> 

function Validation() { 
 
    var x = document.getElementById("username").value; 
 
    var y = document.getElementById("password").value; 
 
    if (x == "") { 
 
    document.getElementById("demo1").innerHTML = "*please write name"; 
 
    } else { 
 
    document.getElementById("demo1").innerHTML = ""; 
 
    } 
 
    if (y == "") { 
 
    document.getElementById("demo2").innerHTML = "*please write password"; 
 
    return false; 
 
    } else { 
 
    document.getElementById("demo2").innerHTML = ""; 
 
    } 
 
}
<div id="form-wrapper"> 
 

 
    <label for="username">UserName </label> 
 
    <input type="text" id="username" name="myuser" onkeyup="Validation()"/><span class="validation" id="demo1"> </span> 
 
    <br/> <br/> 
 
    <label for="password"> Password </label> 
 
    <input type="password" id="password" name="mypassword" onkeyup="Validation()" /> 
 
    <span class="validation" id="demo2"> </span> 
 
    <br /> 
 
    <input type="submit" id="login" value="Log in" onclick="return Validation()" /> <br /> 
 
    <input type="checkbox" checked="checked" /> Remember me 
 
</div>