gpt4 book ai didi

Javascript 表单验证 - 多个大于 0 的表单字段

转载 作者:行者123 更新时间:2023-11-28 10:23:07 26 4
gpt4 key购买 nike

function negativeValues(){
var myTextField = document.getElementById('digit');

if(myTextField.value < 0)
{
alert("Unable to submit as one field has a negative value");
return false;
}
}

上面是一段 Javascript 代码,每次字段 id“digit”的值小于 0 时,提交按钮中的 onsubmit 或 onclick 都会出现一个警告框。

表单中大约有 50 个字段应被视为“数字”字段,其中它们不应小于 0。我应该使用此 Javascript 进行哪些更改以确保所有“数字”之类的字段都有此警报框弹出?

我无法使用 jquery/mootools 进行验证 - 它必须是平面 Javascript。

谢谢。

最佳答案

var form = document.forms[0]; // first form in the document
form.onsubmit = function () {
for (var i=0; i<this.elements.length; i++)
if (Number(this.elements[i].value) < 0) {
alert("Unable to submit as one field has a negative value"); // complain
return false; // and prevent submission
}
}

关于Javascript 表单验证 - 多个大于 0 的表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5063305/

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