技术文摘
JavaScript实现文本框校验及在错误信息前添加图片的方法
2025-01-09 16:41:21 小编
在网页开发中,文本框校验是确保用户输入有效性的重要环节,而在错误信息前添加图片则能让提示更加直观和吸引人。本文将详细介绍如何使用 JavaScript 实现这两个功能。
来看看文本框校验。假设我们有一个简单的 HTML 表单,其中包含一个文本框和一个提交按钮。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文本框校验与图片添加</title>
</head>
<body>
<form id="myForm">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<span id="errorMsg"></span>
<input type="submit" value="提交">
</form>
<script>
const form = document.getElementById('myForm');
const usernameInput = document.getElementById('username');
const errorMsg = document.getElementById('errorMsg');
form.addEventListener('submit', function(event) {
event.preventDefault();
const username = usernameInput.value;
if (username.length < 3) {
errorMsg.textContent = '用户名长度不能少于3位';
} else {
errorMsg.textContent = '';
// 这里可以添加提交表单的逻辑
}
});
</script>
</body>
</html>
在上述代码中,我们通过 addEventListener 监听表单的提交事件。当用户点击提交按钮时,首先阻止表单的默认提交行为,然后获取文本框的值。如果用户名长度小于 3,则在 span 元素中显示错误信息;否则清空错误信息,并可以添加真正提交表单的逻辑。
接下来,在错误信息前添加图片。我们可以在 HTML 中准备好一个图片元素,并将其初始状态设置为隐藏。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文本框校验与图片添加</title>
</head>
<body>
<form id="myForm">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<span id="errorMsg"></span>
<img id="errorIcon" src="error_icon.png" alt="错误图标" style="display: none;">
<input type="submit" value="提交">
</form>
<script>
const form = document.getElementById('myForm');
const usernameInput = document.getElementById('username');
const errorMsg = document.getElementById('errorMsg');
const errorIcon = document.getElementById('errorIcon');
form.addEventListener('submit', function(event) {
event.preventDefault();
const username = usernameInput.value;
if (username.length < 3) {
errorMsg.textContent = '用户名长度不能少于3位';
errorIcon.style.display = 'inline';
errorMsg.insertBefore(errorIcon, errorMsg.firstChild);
} else {
errorMsg.textContent = '';
errorIcon.style.display = 'none';
}
});
</script>
</body>
</html>
在这个更新后的代码中,我们获取了图片元素 errorIcon。当用户名长度不满足要求时,不仅显示错误信息,还将图片显示出来,并通过 insertBefore 方法将图片插入到错误信息之前。当用户名合法时,隐藏图片。
通过以上方法,我们就实现了 JavaScript 文本框校验以及在错误信息前添加图片,提升了用户体验和表单的交互性。
- Python中AttributeError错误:TestEmployee对象为何没有employee属性
- 怎样利用循环简化猜数字小游戏代码
- 人工智能和区块链:是未来革命还是一时泡影
- Golang循环中的 是什么
- 用一个Channel同步多个Go语言协程并确保按顺序执行的方法
- Go语言部署遇难题:在线热更新该如何实现
- 虚拟币充值自动更新余额的实现方法及特定任务完成后的生效机制
- 递归算法实现字符串分割的方法
- Python中IndexError列表索引超出范围错误出现原因及避免方法
- GORM中不创建外键约束进行关联查询的方法
- Go语言中var _ HelloInter = (*Cat)(nil)的作用是什么
- Go语言独特软件包改变游戏规则:提升重复数据删除能力
- 解析具有不同层级竖线字符串的方法
- 用循环和列表解析简化猜数字游戏代码的方法
- Go 代码中传递指针后,为何修改函数内局部变量无法改变指针值