gpt4 book ai didi

javascript - 验证文本字段并将警告文本添加到文本框

转载 作者:行者123 更新时间:2023-11-29 20:12:22 26 4
gpt4 key购买 nike

当名称无效时,我正在尝试向我的文本字段添加警告文本。我有验证代码,但输入无效时无法显示某些文本。

HTML 代码:

<label for="fname">Firstname:</label> 
<input type="text" name="Firstname:" id="fname" size="40" />

Javascript 代码:

fname.onchange = function() {
var fn = /^[a-z\s]{2,30}$/i;
if(!(fn.test(fname.value))) {
//Insert text right to the textbox here!

}
}

最佳答案

DEMO

您可以创建一个跨度来容纳要显示的文本,然后将其插入到文本框之后。为此,您可以在文本框的 nextSibling

之前插入新的跨度
this.parentNode.insertBefore(warningSpan, this.nextSibling);

如果没有nextSibling,那么insertBefore 将足够聪明,将其插入到文本框之后:

完整代码:

var fname  = document.getElementById("fname");
fname.onchange = function() {
var fn = /^[a-z\s]{2,30}$/i;
if(!(fn.test(fname.value))) {
//Insert text right to the textbox here!

var warningSpan = document.createElement("span");
warningSpan.className = "redTextClass";
warningSpan.innerHTML = "Please enter a value";
this.parentNode.insertBefore(warningSpan, this.nextSibling);
} else {
//no validation error, so we better remove it:
var next = this.nextSibling;
if (next && next.className === "redTextClass")
this.parentNode.removeChild(next);
}
}

关于javascript - 验证文本字段并将警告文本添加到文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8767478/

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