2015-05-13 110 views
-4

我想寫一個代碼的幫助,我可以找到代碼的長度,並根據我可以更改錯誤的顏色。如果密碼小於4,那麼它將顯示爲紅色,如果8比黃色,並且如果12比綠色。驗證密碼並根據密碼長度更改其顏色:

我最初的代碼,

<!DOCTYPE html> 
<html> 
<head> 
<script type="text/javascript"> 
function checkPasswordLength(password){ 
    if (password.length > 12) { 
    document.getElementById("errorSpan").innerHTML = "Limit is 12characters"; 
    } 
    else { 
     document.getElementById("errorSpan").innerHTML = ""; 
    } 
} 
</script> 
</head> 
<body> 
<form> 
<input type="password" name="pwd"onchange='checkPasswordLength(this.value)'> 
<span id="errorSpan" style="color:red;"></span> 
</div> 
</form> 
</body> 
</html> 
+0

好的。那麼你的問題是什麼?什麼在工作或不工作?你會得到什麼錯誤? –

+0

應該有足夠的代碼片段來獲取字符串的長度。至於改變顏色,你所要做的就是對document.getElementById(「errorSpan」)。style.color =「#FDFF00」;'爲黃色和'document.getElementById(「errorSpan」)。style.color =「 #FF0000「;'紅色 –

+0

[color hex](http://www.color-hex.com/color/000000) [字符串長度](http://www.w3schools.com/jsref/jsref_length_string.asp ) [更改元素顏色](http://www.w3schools.com/jsref/prop_style_color.asp) –

回答

0

您正在尋找這樣的事情?

function checkPasswordLength(password) { 
 
    var span = document.getElementById("errorSpan"); 
 
    if (password.length >= 12) { 
 
    span.style.color = "green"; 
 
    return; 
 
    } else if (password.length >= 4) { 
 
    span.style.color = "yellow"; 
 
    return; 
 
    } else { 
 
    span.style.color = "red"; 
 
    } 
 
}
<input type="password" name="pwd" onkeyup='checkPasswordLength(this.value)'> 
 
<span id="errorSpan" style="color:red;">****</span>

您已經有了document.getElementById,因此,所有你需要做的是設置爲任何你需要的.style.color。如果您需要更改文本,您可以像使用.innerHTML一樣進行操作。

請注意,我從onchanged更改爲onkeyup,因爲onchanged只會在控件失去焦點時觸發。