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

聖光之護
发布: 2025-10-14 11:44:00
原创
922人浏览过

实现增强型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 += "<input type='hidden' value='" + arr[i] + "'>";
        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'), "<strong>$&</strong>");
            b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
            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'), "<strong>$&</strong>");
    b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
    b.addEventListener("click", function(e) {
        inp.value = this.getElementsByTagName("input")[0].value;
        closeAllLists();
    });
    a.appendChild(b);
}
登录后复制

2.3 输入验证

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

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

百灵大模型
百灵大模型

蚂蚁集团自研的多模态AI大模型系列

百灵大模型 177
查看详情 百灵大模型
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 += "<input type='hidden' value='" + arr[i] + "'>";
        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'), "<strong>$&</strong>");
            b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
            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 功能,包括初始列表显示、模糊匹配和输入验证。这些功能可以显著提升用户体验和数据质量。在实际应用中,可以根据具体需求进行进一步的优化和定制。

以上就是实现增强型Autocomplete:模糊匹配、初始列表显示及输入验证的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

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