0

0

实现增强型Autocomplete:模糊匹配、初始列表显示及输入验证

聖光之護

聖光之護

发布时间:2025-10-14 11:44:00

|

936人浏览过

|

来源于php中文网

原创

实现增强型autocomplete:模糊匹配、初始列表显示及输入验证

本文将指导你如何增强现有的Autocomplete功能,实现以下目标:在输入框获得焦点时显示完整列表、支持模糊匹配(即在字符串的任何位置进行匹配),以及限制用户输入,确保只能输入Autocomplete列表中存在的值。通过本文,你将学习如何修改现有的JavaScript代码,使其满足这些需求,从而提升用户体验和数据质量。

1. 需求分析

在开始修改代码之前,我们先明确需要实现的功能:

  • 初始列表显示: 当用户点击输入框(获得焦点)时,如果输入框为空,则显示完整的Autocomplete选项列表。
  • 模糊匹配: 搜索时,不仅匹配字符串的开头,还要匹配字符串中任何位置出现的字符。
  • 输入验证: 限制用户只能输入Autocomplete列表中存在的值,防止用户输入任意内容。

2. 代码实现

我们将逐步修改提供的 JavaScript 代码,以实现上述功能。

2.1 初始列表显示

修改 inp.addEventListener("input", function(e) { ... }); 为 inp.addEventListener("focus", function(e) { ... }); 和添加 inp.addEventListener("input", function(e) { ... });,并在 focus 事件处理函数中添加显示完整列表的逻辑。

inp.addEventListener("focus", function(e) {
    var a, b, i, val = this.value;
    closeAllLists();
    currentFocus = -1;
    a = document.createElement("DIV");
    a.setAttribute("id", this.id + "autocomplete-list");
    a.setAttribute("class", "autocomplete-items");
    this.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);
    }
});

inp.addEventListener("input", function(e) {
    var a, b, i, val = this.value;
    closeAllLists();
    if (!val) {
        return false;
    }
    currentFocus = -1;
    a = document.createElement("DIV");
    a.setAttribute("id", this.id + "autocomplete-list");
    a.setAttribute("class", "autocomplete-items");
    this.parentNode.appendChild(a);

    for (i = 0; i < arr.length; i++) {
        if (arr[i].toUpperCase().indexOf(val.toUpperCase()) > -1) {
            b = document.createElement("DIV");
            b.innerHTML = arr[i].replace(new RegExp(val, 'gi'), "$&");
            b.innerHTML += "";
            b.addEventListener("click", function(e) {
                inp.value = this.getElementsByTagName("input")[0].value;
                closeAllLists();
            });
            a.appendChild(b);
        }
    }
});

2.2 模糊匹配

修改 if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) 为 if (arr[i].toUpperCase().indexOf(val.toUpperCase()) > -1),实现模糊匹配。同时,优化匹配项的显示,高亮匹配的部分。

if (arr[i].toUpperCase().indexOf(val.toUpperCase()) > -1) {
    b = document.createElement("DIV");
    b.innerHTML = arr[i].replace(new RegExp(val, 'gi'), "$&");
    b.innerHTML += "";
    b.addEventListener("click", function(e) {
        inp.value = this.getElementsByTagName("input")[0].value;
        closeAllLists();
    });
    a.appendChild(b);
}

2.3 输入验证

为了实现输入验证,我们需要在表单提交时检查输入框的值是否在Autocomplete列表中。

首先,获取表单元素和 Autocomplete 列表:

Cogram
Cogram

使用AI帮你做会议笔记,跟踪行动项目

下载
const form = document.getElementById("regForm");
const fruitInput = document.getElementById("myFruitList");

然后,添加表单提交事件监听器,进行验证:

form.addEventListener("submit", function(e) {
  const inputValue = fruitInput.value;
  const isValid = fruitlist.includes(inputValue);

  if (!isValid) {
    e.preventDefault(); // 阻止表单提交
    alert("Please select a valid fruit from the list.");
    fruitInput.classList.add("invalid"); // 添加错误样式
  } else {
    fruitInput.classList.remove("invalid"); // 移除错误样式
  }
});

同时,添加 blur 事件监听器,在输入框失去焦点时进行验证,并提供实时反馈:

fruitInput.addEventListener("blur", function() {
  const inputValue = fruitInput.value;
  const isValid = fruitlist.includes(inputValue);

  if (!isValid && inputValue !== "") {
    fruitInput.classList.add("invalid");
  } else {
    fruitInput.classList.remove("invalid");
  }
});

在 CSS 中添加 .invalid 样式:

input.invalid {
  background-color: #ffdddd;
}

3. 完整代码

以下是修改后的完整 JavaScript 代码:

function autocomplete(inp, arr) {
  var currentFocus;
  inp.addEventListener("focus", function(e) {
    var a, b, i, val = this.value;
    closeAllLists();
    currentFocus = -1;
    a = document.createElement("DIV");
    a.setAttribute("id", this.id + "autocomplete-list");
    a.setAttribute("class", "autocomplete-items");
    this.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);
    }
  });

  inp.addEventListener("input", function(e) {
    var a, b, i, val = this.value;
    closeAllLists();
    if (!val) {
      return false;
    }
    currentFocus = -1;
    a = document.createElement("DIV");
    a.setAttribute("id", this.id + "autocomplete-list");
    a.setAttribute("class", "autocomplete-items");
    this.parentNode.appendChild(a);

    for (i = 0; i < arr.length; i++) {
        if (arr[i].toUpperCase().indexOf(val.toUpperCase()) > -1) {
            b = document.createElement("DIV");
            b.innerHTML = arr[i].replace(new RegExp(val, 'gi'), "$&");
            b.innerHTML += "";
            b.addEventListener("click", function(e) {
                inp.value = this.getElementsByTagName("input")[0].value;
                closeAllLists();
            });
            a.appendChild(b);
        }
    }
  });

  inp.addEventListener("keydown", function(e) {
    var x = document.getElementById(this.id + "autocomplete-list");
    if (x) x = x.getElementsByTagName("div");
    if (e.keyCode == 40) {
      currentFocus++;
      addActive(x);
    } else if (e.keyCode == 38) {
      currentFocus--;
      addActive(x);
    } else if (e.keyCode == 13) {
      e.preventDefault();
      if (currentFocus > -1) {
        if (x) x[currentFocus].click();
      }
    }
  });

  function addActive(x) {
    if (!x) return false;
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    x[currentFocus].classList.add("autocomplete-active");
  }

  function removeActive(x) {
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }

  function closeAllLists(elmnt) {
    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]);
      }
    }
  }

  document.addEventListener("click", function(e) {
    closeAllLists(e.target);
  });
}

var fruitlist = [
  "Apple",
  "Mango",
  "Pear",
  "Banana",
  "Berry"
];

autocomplete(document.getElementById("myFruitList"), fruitlist);

const form = document.getElementById("regForm");
const fruitInput = document.getElementById("myFruitList");

form.addEventListener("submit", function(e) {
  const inputValue = fruitInput.value;
  const isValid = fruitlist.includes(inputValue);

  if (!isValid) {
    e.preventDefault();
    alert("Please select a valid fruit from the list.");
    fruitInput.classList.add("invalid");
  } else {
    fruitInput.classList.remove("invalid");
  }
});

fruitInput.addEventListener("blur", function() {
  const inputValue = fruitInput.value;
  const isValid = fruitlist.includes(inputValue);

  if (!isValid && inputValue !== "") {
    fruitInput.classList.add("invalid");
  } else {
    fruitInput.classList.remove("invalid");
  }
});

4. 注意事项

  • 性能优化: 对于大型数据集,模糊匹配可能会影响性能。可以考虑使用更高效的搜索算法或对数据进行预处理。
  • 用户体验: 在输入验证时,提供清晰的错误提示,帮助用户选择正确的值。
  • 安全性: 在服务器端进行数据验证,防止恶意用户绕过客户端验证。

5. 总结

通过修改 JavaScript 代码,我们成功实现了增强型的 Autocomplete 功能,包括初始列表显示、模糊匹配和输入验证。这些功能可以显著提升用户体验和数据质量。在实际应用中,可以根据具体需求进行进一步的优化和定制。

相关专题

更多
js获取数组长度的方法
js获取数组长度的方法

在js中,可以利用array对象的length属性来获取数组长度,该属性可设置或返回数组中元素的数目,只需要使用“array.length”语句即可返回表示数组对象的元素个数的数值,也就是长度值。php中文网还提供JavaScript数组的相关下载、相关课程等内容,供大家免费下载使用。

540

2023.06.20

js刷新当前页面
js刷新当前页面

js刷新当前页面的方法:1、reload方法,该方法强迫浏览器刷新当前页面,语法为“location.reload([bForceGet]) ”;2、replace方法,该方法通过指定URL替换当前缓存在历史里(客户端)的项目,因此当使用replace方法之后,不能通过“前进”和“后退”来访问已经被替换的URL,语法为“location.replace(URL) ”。php中文网为大家带来了js刷新当前页面的相关知识、以及相关文章等内容

372

2023.07.04

js四舍五入
js四舍五入

js四舍五入的方法:1、tofixed方法,可把 Number 四舍五入为指定小数位数的数字;2、round() 方法,可把一个数字舍入为最接近的整数。php中文网为大家带来了js四舍五入的相关知识、以及相关文章等内容

727

2023.07.04

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

470

2023.09.01

JavaScript转义字符
JavaScript转义字符

JavaScript中的转义字符是反斜杠和引号,可以在字符串中表示特殊字符或改变字符的含义。本专题为大家提供转义字符相关的文章、下载、课程内容,供大家免费下载体验。

391

2023.09.04

js生成随机数的方法
js生成随机数的方法

js生成随机数的方法有:1、使用random函数生成0-1之间的随机数;2、使用random函数和特定范围来生成随机整数;3、使用random函数和round函数生成0-99之间的随机整数;4、使用random函数和其他函数生成更复杂的随机数;5、使用random函数和其他函数生成范围内的随机小数;6、使用random函数和其他函数生成范围内的随机整数或小数。

990

2023.09.04

如何启用JavaScript
如何启用JavaScript

JavaScript启用方法有内联脚本、内部脚本、外部脚本和异步加载。详细介绍:1、内联脚本是将JavaScript代码直接嵌入到HTML标签中;2、内部脚本是将JavaScript代码放置在HTML文件的`<script>`标签中;3、外部脚本是将JavaScript代码放置在一个独立的文件;4、外部脚本是将JavaScript代码放置在一个独立的文件。

653

2023.09.12

Js中Symbol类详解
Js中Symbol类详解

javascript中的Symbol数据类型是一种基本数据类型,用于表示独一无二的值。Symbol的特点:1、独一无二,每个Symbol值都是唯一的,不会与其他任何值相等;2、不可变性,Symbol值一旦创建,就不能修改或者重新赋值;3、隐藏性,Symbol值不会被隐式转换为其他类型;4、无法枚举,Symbol值作为对象的属性名时,默认是不可枚举的。

543

2023.09.20

桌面文件位置介绍
桌面文件位置介绍

本专题整合了桌面文件相关教程,阅读专题下面的文章了解更多内容。

0

2025.12.30

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
Sass 教程
Sass 教程

共14课时 | 0.7万人学习

Bootstrap 5教程
Bootstrap 5教程

共46课时 | 2.7万人学习

CSS教程
CSS教程

共754课时 | 17.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号