我正在尝试通过一些表单验证来提高我的javascript技能。为什么我的代码不起作用?
<input type="password" id="psw" />
<p id="demo" ></p>
<script type="text/javascript" >
psw.oninput = function(event) {
myArray = ["1", "2","3","4","5","6","7","8","9"];
for(x=0; x<myArray.length; x++){
if(this.value.includes(myArray[x]){
demo.innerHTML = "password cannot include
a number";
} else{
demo.innerHTML = "";
}
</script>
答案 0 :(得分:1)
您正试图错误地绑定input
事件
psw.oninput = function(event)
^
使用函数psw
getElementById
document.getElementById('psw')
^
您未正确分配字符串
demo.innerHTML = "password cannot include
a number"; ^
^
缺少括号括号
if(this.value.includes(myArray[x])
^
当this.value.includes(myArray[x])
为真时,你需要打破循环。
带有这些修补程序的代码段
document.getElementById('psw').addEventListener('input', function(event) {
var myArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
for (var x = 0; x < myArray.length; x++) {
if (this.value.includes(myArray[x])) {
demo.innerHTML = "password cannot include a number ";
break; // you need to break your loop
} else {
demo.innerHTML = "";
}
}
});
&#13;
<input type="password" id="psw" />
<p id='demo'></p>
&#13;
答案 1 :(得分:0)
这样可行。
只有在输入数字9时才显示文本,如果您输入任何其他数字,则不会显示。为什么呢?
如果您输入5
,则会插入password cannot include a number
,因为它会循环播放,并且由于字符串中不存在6
,因此会清除警报。
<input type="password" id="psw" />
<p id="demo"></p>
<script type="text/javascript" >
var psw = document.getElementById("psw");
var demo = document.getElementById("demo");
psw.oninput = function(event) {
var isnumberpresent = false;
myArray = ["1", "2","3","4","5","6","7","8","9"];
for(var x=0; x<myArray.length; x++)
{
if(this.value.includes(myArray[x]))
{
isnumberpresent = true;
}
}
demo.innerHTML = isnumberpresent ? "password cannot include a number":"";
};
</script>
&#13;
答案 2 :(得分:0)
这是一项非常基本的改进。但是,如果您尝试提高Javascript技能,请考虑使用正则表达式作为建议。
<input type="password" id="psw" oninput="validate(this.value)" />
<p id="demo" ></p>
<script type="text/javascript" >
function validate(password) {
var demo = document.getElementById('demo');
var myArray = ["1", "2","3","4","5","6","7","8","9"];
for(x=0; x<myArray.length; x++){
if(password.includes(myArray[x])){
demo.innerHTML = "password cannot include a number";
break;
} else{
demo.innerHTML = "";
}
}
}
</script>
答案 3 :(得分:0)
此代码正常运行。关闭if括号。使用适当的编辑器编写像notepad ++这样的代码。
<!DOCTYPE html>
<html>
<body>
<p>Write something in the text field to trigger a function.</p>
<input type="text" id="psw"/>
<p id="demo"></p>
<script>
var x;
psw.oninput = function myfunc(){
var myArray = ["1", "2","3","4","5","6","7","8","9"];
var ele=document.getElementById("psw").value;
for(x=0; x<myArray.length; x++){
if(myArray.includes(ele)){
demo.innerHTML = "password cannot include a number";
}
else { demo.innerHTML = ""; }
}
}
</script>
</body>
</html>