gpt4 book ai didi

javascript - 仅添加整数验证?

转载 作者:行者123 更新时间:2023-11-29 15:03:07 25 4
gpt4 key购买 nike

我有一个脚本在提交时循环遍历所有带有 class="validate" 的元素,如果它们为空,则取消提交并更改它们的背景颜色。任何人都知道我可以在同一个函数中添加第二个验证的方法,以确保带有 class="validate2" 的 elemnets 只是数字(没有文字)?这是我的脚本:

<script type="text/javascript" >
window.onload = function() {
document.getElementById("formID").onsubmit = function() {
var fields = this.getElementsByClassName("validate"),
sendForm = true,
flag=false;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ffb8b8";
flag=true;

sendForm = false;
window.scrollTo(0,0);
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
</script>

最佳答案

试试这个方法:

<script type="text/javascript" >
window.onload = function() {
document.getElementById("formID").onsubmit = function() {
var fields = this.elements;
sendForm = true;
var flag=false;

for(var i = 0; i < fields.length; i++) {
if (fields[i].className == 'validate' || fields[i].className == 'validate2') {
alert(fields[i].className);
if (fields[i].value.length == 0) {
fields[i].style.backgroundColor = "#ffb8b8";
flag=true;
sendForm = false;
window.scrollTo(0,0);
}
else if (fields[i].className == 'validate2' && isNaN(Number(fields[i].value))) {
fields[i].style.backgroundColor = "#ffb8b8";
flag=true;
sendForm = false;
window.scrollTo(0,0);
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
}

if(!sendForm) {
return false;
}
}

}

关于javascript - 仅添加整数验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7352313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com