gpt4 book ai didi

JavaScript 表单验证

转载 作者:行者123 更新时间:2023-12-03 08:56:45 25 4
gpt4 key购买 nike

这个脚本有问题吗?

function validation() {
var message, x;
message = document.getElementsByClassName("message");
message.innerHTML = "";
x = document.getElementsByClassName("inputNumber").value;

try {

if(isNaN(x)) throw "Input is not a number";

}
catch(err) {
message.innerHTML = err;
}

}

HTML 是这样的:

    <input type="number" class="form-control inputNumber" onkeyup="validation()" >
<div class="help-block with-errors"></div>
<p class="message"></p>

控制台没有显示任何错误,但验证没有发生。

最佳答案

试试这个:

Just for testing purpose I have set type='text'. I have passed the current context of the input field as an argument so that I can relate other closest elements using that context.

function validation(elem) {
var message, x;
message = elem.nextElementSibling.nextElementSibling;
message.innerHTML = "";
x = elem.value;
if (isNaN(x)) {
message.innerHTML = "Input is not a number";
}
}
<input type="text" class="form-control inputNumber" onkeyup="validation(this)">

<div class="help-block with-errors"></div>
<p class="message"></p>

关于JavaScript 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32458645/

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