实现更强大的HTML表单自动完成功能:模糊匹配、光标悬停显示全部选项以及输入验证

实现更强大的html表单自动完成功能:模糊匹配、光标悬停显示全部选项以及输入验证

本文将指导你如何增强HTML表单的自动完成功能,使其具备以下特性:在光标悬停时显示所有选项,支持在字符串的任何位置进行模糊匹配,并强制用户输入的内容必须是自动完成列表中的有效值。我们将通过修改现有的JavaScript代码,并添加必要的验证逻辑来实现这些功能。

1. 光标悬停时显示所有选项

要实现光标悬停时显示所有选项,我们需要修改 fruitautocomplete 函数中的事件监听器。当输入框获得焦点时,如果输入框为空,则显示完整的 fruitlist。

inp.addEventListener("focus", function(e) {  if (!this.value) {    showAllOptions(this, fruitlist);  }});function showAllOptions(inp, arr) {  var a, b, i, val = ""; // val设为空,显示所有项  closeAllLists();  currentFocus = -1;  a = document.createElement("DIV");  a.setAttribute("id", inp.id + "autocomplete-list");  a.setAttribute("class", "autocomplete-items");  inp.parentNode.appendChild(a);  for (i = 0; i < arr.length; i++) {      b = document.createElement("DIV");      b.innerHTML = arr[i];      b.innerHTML += "";      b.addEventListener("click", function(e) {          inp.value = this.getElementsByTagName("input")[0].value;          closeAllLists();      });      a.appendChild(b);  }}

这段代码添加了一个 focus 事件监听器,当输入框获得焦点且内容为空时,调用 showAllOptions 函数。 showAllOptions 函数与原有的自动完成逻辑类似,但它会显示 fruitlist 中的所有选项,而不管输入框中的内容是什么。

2. 支持在字符串的任何位置进行模糊匹配

为了支持模糊匹配,我们需要修改自动完成逻辑中的字符串比较部分。不再使用 substr 和 toUpperCase 来检查字符串是否以输入框中的内容开头,而是使用 indexOf 来检查字符串是否包含输入框中的内容。

立即学习“前端免费学习笔记(深入)”;

if (arr[i].toUpperCase().indexOf(val.toUpperCase()) > -1) {  /*create a DIV element for each matching element:*/  b = document.createElement("DIV");  /*make the matching letters bold:*/  let index = arr[i].toUpperCase().indexOf(val.toUpperCase());  b.innerHTML = arr[i].substr(0, index);  b.innerHTML += "" + arr[i].substr(index, val.length) + "";  b.innerHTML += arr[i].substr(index + val.length);  /*insert a input field that will hold the current array item's value:*/  b.innerHTML += "";  /*execute a function when someone clicks on the item value (DIV element):*/  b.addEventListener("click", function(e) {    /*insert the value for the autocomplete text field:*/    inp.value = this.getElementsByTagName("input")[0].value;    /*close the list of autocompleted values,    (or any other open lists of autocompleted values:*/    closeAllLists();  });  a.appendChild(b);}

这段代码使用 indexOf 函数来查找 arr[i] 中是否包含 val。如果 indexOf 返回值大于 -1,则表示 arr[i] 包含 val,我们就创建一个包含匹配项的 DIV 元素。

3. 强制用户输入的内容必须是自动完成列表中的有效值

要强制用户输入的内容必须是自动完成列表中的有效值,我们需要添加输入验证逻辑。可以在表单提交时进行验证,或者在输入框失去焦点时进行验证。这里我们选择在输入框失去焦点时进行验证。

inp.addEventListener("blur", function(e) {  let valid = false;  for (let i = 0; i < fruitlist.length; i++) {    if (fruitlist[i] === this.value) {      valid = true;      break;    }  }  if (!valid) {    this.value = ""; // Clear the input if it's invalid    alert("Please select a valid fruit from the list.");  }});

这段代码添加了一个 blur 事件监听器,当输入框失去焦点时,它会检查输入框中的值是否在 fruitlist 中。如果不在,则清空输入框并显示警告信息。

完整代码示例

* {  box-sizing: border-box;}body {  background-color: #f1f1f1;}#regForm {  background-color: #ffffff;  margin: 10px auto;  font-family: Raleway;  padding: 10px;  width: 90%;  min-width: 300px;}h1 {  text-align: center;}input {  padding: 10px;  width: 100%;  font-size: 17px;  font-family: Raleway;  border: 1px solid #aaaaaa;}/* Mark input boxes that gets an error on validation: */input.invalid {  background-color: #ffdddd;}/* Hide all steps by default: */.tab {  display: none;}button {  background-color: #04AA6D;  color: #ffffff;  border: none;  padding: 10px 20px;  font-size: 17px;  font-family: Raleway;  cursor: pointer;}button:hover {  opacity: 0.8;}#prevBtn {  background-color: #bbbbbb;}/* Make circles that indicate the steps of the form: */.step {  height: 15px;  width: 15px;  margin: 0 2px;  background-color: #bbbbbb;  border: none;  border-radius: 50%;  display: inline-block;  opacity: 0.5;}.step.active {  opacity: 1;}/* Mark the steps that are finished and valid: */.step.finish {  background-color: #04AA6D;}.autocomplete {  position: relative;  display: inline-block;}.autocomplete-items {  position: absolute;  border: 1px solid #d4d4d4;  border-bottom: none;  border-top: none;  z-index: 99;  /*position the autocomplete items to be the same width as the container:*/  top: 100%;  left: 0;  right: 0;}.autocomplete-items div {  padding: 10px;  cursor: pointer;  background-color: #fff;  border-bottom: 1px solid #d4d4d4;}.autocomplete-items div:hover {  /*when hovering an item:*/  background-color: #e9e9e9;}.autocomplete-active {  /*when navigating through the items using the arrow keys:*/  background-color: DodgerBlue !important;  color: #ffffff;}  

Your Nutrition Needs:

Your Fruit:

function fruitautocomplete(inp, arr) { /*the autocomplete function takes two arguments, the text field element and an array of possible autocompleted values:*/ var currentFocus; /*execute a function when someone writes in the text field:*/ inp.addEventListener("input", function(e) { var a, b, i, val = this.value; /*close any already open lists of autocompleted values*/ closeAllLists(); if (!val) { return false; } currentFocus = -1; /*create a DIV element that will contain the items (values):*/ a = document.createElement("DIV"); a.setAttribute("id", this.id + "autocomplete-list"); a.setAttribute("class", "autocomplete-items"); /*append the DIV element as a child of the autocomplete container:*/ this.parentNode.appendChild(a); /*for each item in the array...*/ for (i = 0; i -1) { /*create a DIV element for each matching element:*/ b = document.createElement("DIV"); /*make the matching letters bold:*/ let index = arr[i].toUpperCase().indexOf(val.toUpperCase()); b.innerHTML = arr[i].substr(0, index); b.innerHTML += "" + arr[i].substr(index, val.length) + ""; b.innerHTML += arr[i].substr(index + val.length); /*insert a input field that will hold the current array item's value:*/ b.innerHTML += ""; /*execute a function when someone clicks on the item value (DIV element):*/ b.addEventListener("click", function(e) { /*insert the value for the autocomplete text field:*/ inp.value = this.getElementsByTagName("input")[0].value; /*close the list of autocompleted values, (or any other open lists of autocompleted values:*/ closeAllLists(); }); a.appendChild(b); } } }); /*execute a function presses a key on the keyboard:*/ inp.addEventListener("keydown", function(e) { var x = document.getElementById(this.id + "autocomplete-list"); if (x) x = x.getElementsByTagName("div"); if (e.keyCode == 40) { /*If the arrow DOWN key is pressed, increase the currentFocus variable:*/ currentFocus++; /*and and make the current item more visible:*/ addActive(x); } else if (e.keyCode == 38) { //up /*If the arrow UP key is pressed, decrease the currentFocus variable:*/ currentFocus--; /*and and make the current item more visible:*/ addActive(x); } else if (e.keyCode == 13) { /*If the ENTER key is pressed, prevent the form from being submitted,*/ e.preventDefault(); if (currentFocus > -1) { /*and simulate a click on the "active" item:*/ if (x) x[currentFocus].click(); } } }); inp.addEventListener("focus", function(e) { if (!this.value) { showAllOptions(this, fruitlist); } }); inp.addEventListener("blur", function(e) { let valid = false; for (let i = 0; i = x.length) currentFocus = 0; if (currentFocus < 0) currentFocus = (x.length - 1); /*add class "autocomplete-active":*/ x[currentFocus].classList.add("autocomplete-active"); } function removeActive(x) { /*a function to remove the "active" class from all autocomplete items:*/ for (var i = 0; i < x.length; i++) { x[i].classList.remove("autocomplete-active"); } } function closeAllLists(elmnt) { /*close all autocomplete lists in the document, except the one passed as an argument:*/ var x = document.getElementsByClassName("autocomplete-items"); for (var i = 0; i < x.length; i++) { if (elmnt != x[i] && elmnt != inp) { x[i].parentNode.removeChild(x[i]); } } } function showAllOptions(inp, arr) { var a, b, i, val = ""; // val设为空,显示所有项 closeAllLists(); currentFocus = -1; a = document.createElement("DIV"); a.setAttribute("id", inp.id + "autocomplete-list"); a.setAttribute("class", "autocomplete-items"); inp.parentNode.appendChild(a); for (i = 0; i < arr.length; i++) { b = document.createElement("DIV"); b.innerHTML = arr[i]; b.innerHTML += ""; b.addEventListener("click", function(e) { inp.value = this.getElementsByTagName("input")[0].value; closeAllLists(); }); a.appendChild(b); } } /*execute a function when someone clicks in the document:*/ document.addEventListener("click", function(e) { closeAllLists(e.target); });}/*An array containing all the country names in the world:*/var fruitlist = [ "Apple", "Mango", "Pear", "Banana", "Berry"];/*initiate the autocomplete function on the "myFruitList" element, and pass along the fruit array as possible autocomplete values:*/fruitautocomplete(document.getElementById("myFruitList"), fruitlist);

注意事项

性能: 对于大型数据集,模糊匹配可能会影响性能。可以考虑使用更高效的搜索算法或限制显示的选项数量。用户体验: 确保自动完成列表的样式与你的网站风格一致。可访问性: 确保自动完成功能对使用屏幕阅读器等辅助技术的用户是可访问的。

总结

通过修改 JavaScript 代码,我们成功地增强了 HTML 表单的自动完成功能,使其具备了光标悬停时显示所有选项、支持模糊匹配和强制输入验证的能力。这些改进可以显著提升用户体验,并确保用户输入的数据是有效的。 请记住,根据你的具体需求,你可能需要进一步调整代码。 例如,你可能需要添加错误处理、自定义样式或与其他 JavaScript 库集成。

以上就是实现更强大的HTML表单自动完成功能:模糊匹配、光标悬停显示全部选项以及输入验证的详细内容,更多请关注php中文网其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1324161.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
WordPress主题模板结构差异:传统主题 vs. FSE主题
上一篇 2025年12月12日 10:51:30
Laravel 延迟队列任务执行指南:解决任务挂起问题
下一篇 2025年12月12日 10:51:42

相关推荐

  • composer require-dev和require有什么不同_Composer Require与Require-Dev区别解析

    require用于声明项目运行必需的依赖,如框架、数据库组件和第三方SDK,这些包会随项目部署到生产环境;2. require-dev用于声明仅在开发和测试阶段需要的工具,如PHPUnit、PHPStan、Faker等,不会默认部署到生产环境;3. 安装时composer install根据环境决定…

    2026年5月10日
    1000
  • 修复Django电商项目中AJAX过滤产品列表图片不显示问题

    在Django电商项目中,当使用AJAX动态加载过滤后的产品列表时,常遇到图片无法正常显示的问题。这通常是由于前端模板中图片加载方式(如data-setbg属性结合JavaScript库)与AJAX动态内容更新机制不兼容所致。解决方案是直接在AJAX返回的HTML中使用标准的标签来渲染图片,确保浏览…

    2026年5月10日
    700
  • 开源免费PHP工具 PHP开发效率提升利器

    推荐开源免费PHP开发工具以提升效率:VS Code、Sublime Text轻量高效,PhpStorm专业强大;调试用Xdebug、Kint、Ray;依赖管理选Composer;代码质量工具包括PHPStan、Psalm、PHP_CodeSniffer;数据库管理可用%ignore_a_1%MyA…

    2026年5月10日
    000
  • Matplotlib 地图中多类型图例的创建与优化

    Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化Matplotlib 地图中多类型图例的创建与优化

    本教程旨在解决matplotlib地图可视化中,如何在一个图例中同时展示颜色块(如区域分类)和自定义标记(如特定兴趣点)的问题。文章详细介绍了当传统`patch`对象无法正确显示标记时,如何利用`matplotlib.lines.line2d`创建标记图例句柄,并将其与颜色块图例句柄合并,从而生成一…

    2026年5月10日 用户投稿
    900
  • Golang JSON序列化:控制敏感字段暴露的最佳实践

    本教程探讨golang中如何高效控制结构体字段在json序列化时的可见性。当需要将包含敏感信息的结构体数组转换为json响应时,通过利用`encoding/json`包提供的结构体标签,特别是`json:”-“`,可以轻松实现对特定字段的忽略,从而避免敏感数据泄露,确保api…

    2026年5月10日
    300
  • 怎么在PHP代码中实现图片上传功能_PHP图片上传功能实现与安全处理教程

    首先创建含enctype的HTML表单,再用PHP接收文件,检查目录、移动临时文件,验证类型与大小,生成唯一文件名,并调整php.ini限制以确保上传成功。 如果您尝试在PHP项目中添加图片上传功能,但服务器无法正确接收或保存文件,则可能是由于表单配置、文件处理逻辑或安全限制的问题。以下是实现该功能…

    2026年5月10日
    300
  • 获取日期中的周数:CodeIgniter 教程

    本教程旨在帮助开发者在 CodeIgniter 框架中,从日期字符串中准确提取周数。我们将使用 PHP 内置的 DateTime 类,并提供详细的代码示例和注意事项,确保您能够轻松地在项目中实现此功能。 使用 DateTime 类获取周数 PHP 的 DateTime 类提供了一种便捷的方式来处理日…

    2026年5月10日
    100
  • 比特币新手教程 比特币交易平台有哪些

    比特币是一种去中心化的数字货币,基于区块链技术实现点对点交易,具有匿名性、有限发行和不可篡改等特点;新手可通过交易所购买,P2P交易获得比特币,常用平台包括Binance、OKX和Huobi;交易流程包括注册账户、实名认证、绑定支付方式、充值法币并下单购买,可选择市价单或限价单;比特币存储方式有交易…

    2026年5月10日
    000
  • c++中的SFINAE技术是什么_c++模板编程中的SFINAE原理与应用

    SFINAE 是“替换失败不是错误”的原则,指模板实例化时若参数替换导致错误,只要存在其他合法候选,编译器不报错而是继续重载决议。它用于条件启用模板、类型检测等场景,如通过 decltype 或 enable_if 控制函数重载,实现类型特征判断。尽管 C++20 引入 Concepts 简化了部分…

    2026年5月10日
    000
  • HTML如何隐藏滚动条或去除滚动条

    滚动条可以存在也可以不存在,本文主要介绍了html 隐藏滚动条和去除滚动条的方法的相关资料,大家一起来学习一下html隐藏滚动条或去除滚动条的方法吧。 1. html 标签加属性 XML/HTML Code复制内容到剪贴板 2.body中加入以下代码 立即学习“前端免费学习笔记(深入)”; html…

    用户投稿 2026年5月10日
    100
  • Golang gRPC流式请求异常处理

    在Golang的gRPC流式通信中,必须通过context.Context处理异常。应监听上下文取消或超时,及时释放资源,设置合理超时,避免连接长时间挂起,并在goroutine中通过context控制生命周期。 在使用 Golang 和 gRPC 实现流式通信时,异常处理是确保服务健壮性的关键部分…

    2026年5月10日
    000
  • Go语言mgo查询构建:深入理解bson.M与日期范围查询的正确实践

    本文旨在解决go语言mgo库中构建复杂查询时,特别是涉及嵌套`bson.m`和日期范围筛选的常见错误。我们将深入剖析`bson.m`的类型特性,解释为何直接索引`interface{}`会导致“invalid operation”错误,并提供一种推荐的、结构清晰的代码重构方案,以确保查询条件能够正确…

    2026年5月10日
    100
  • vscode上怎么运行html_vscode上运行html步骤【指南】

    首先保存文件为.html格式,再通过浏览器或Live Server插件打开预览;推荐安装Live Server实现本地服务器运行与实时刷新,提升开发体验。 在 VS Code 上运行 HTML 文件并不需要复杂的配置,只需几个简单步骤即可预览页面效果。VS Code 本身是一个代码编辑器,不直接运行…

    2026年5月10日
    100
  • 修复点击时按钮抖动:CSS垂直对齐实践

    本文探讨了在Web开发中,交互式按钮(如播放/暂停按钮)在点击时发生意外垂直位移的问题。通过分析CSS样式变化对元素布局的影响,我们发现这是由于按钮不同状态下的边框样式和内边距改变,以及默认的垂直对齐行为共同作用所致。核心解决方案是利用CSS的vertical-align属性,将其设置为middle…

    2026年5月10日
    100
  • Golang goroutine与channel调试技巧

    使用go run -race检测数据竞争,结合runtime.NumGoroutine监控协程数量,通过pprof分析阻塞调用栈,利用select超时避免永久阻塞,有效排查goroutine泄漏、死锁和数据竞争问题。 Go语言的goroutine和channel是并发编程的核心,但它们也带来了调试上…

    2026年5月10日
    000
  • 页面中文本域的值怎么设置

    标签定义多行的文本输入控件。 文本区中可容纳无限数量的文本,其中的文本的默认字体是等宽字体(通常是 Courier)。 可以通过 cols 和 rows 属性来规定 textarea 的尺寸,不过更好的办法是使用 CSS 的 height 和 width 属性。 注释:在文本输入区内的文本行间,用 …

    2026年5月10日
    000
  • 《魔兽世界》将于6月11日开启国服回归技术测试

    《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试《魔兽世界》将于6月11日开启国服回归技术测试

    《%ign%ignore_a_1%re_a_1%》官方宣布,将于6月11日开启国服回归技术测试,时间为7天,并称可以在6月内正式开服,玩家们可以访问官网下载战网客户端并预下载“巫妖王之怒”客户端,技术测试详情见下图。 WordAi WordAI是一个AI驱动的内容重写平台 53 查看详情 以上就是《…

    2026年5月10日 用户投稿
    400
  • 使用 Jupyter Notebook 进行探索性数据分析

    Jupyter Notebook通过单元格实现代码与Markdown结合,支持数据导入(pandas)、清洗(fillna)、探索(matplotlib/seaborn可视化)、统计分析(describe/corr)和特征工程,便于记录与分享分析过程。 Jupyter Notebook 是进行探索性…

    2026年5月10日
    000
  • php常量怎么用_PHP常量(define/const)定义与使用方法

    PHP中可通过define函数和const关键字定义常量,用于存储不可变值。define适用于全局作用域,支持动态名称和条件定义,如define(‘SITE_NAME’, ‘MyWebsite’);const在编译时生效,语法简洁但限制多,只能在类或全…

    2026年5月10日
    000
  • 如何在HTML中插入表单元素_HTML表单控件与输入类型使用指南

    HTML表单通过标签构建,包含action和method属性定义数据提交目标与方式,常用input类型如text、password、email等适配不同输入需求,配合label、required、placeholder提升可用性,结合textarea、select、button等控件实现完整交互,是…

    2026年5月10日
    300

发表回复

登录后才能评论
关注微信