You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Autocomplete代码支持多字段数据源并提交至PHP

多字段对象数组的自动补全实现(适配AJAX表单)

我不精通JavaScript,希望将单值数组的自动补全示例改成支持多字段对象数组的版本,数据源为包含label、value、id的对象数组,示例如下:

[{
  label: "Afghanistan",
  value: 100,
  id: 1, 
},
{
  label: "Albania",
  value: 101,
  id: 2, 
},
{
  label: "Algeria",
  value: 102,
  id: 3, 
}]

同时要求AJAX表单提交时,PHP能获取选中项的所有字段值。以下是完整修改方案:


1. 整合自动补全的HTML表单

在原有AJAX表单中添加自动补全输入框,以及用于存储选中项字段的隐藏输入框:

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">      
  <!-- 原有复选框字段 -->
  <input type="checkbox" name="myfield1" value="myfield1">
  <label for="myfield1"><span id="text_myfield1">Myfield1</span></label>
  <input type="checkbox" name="myfield2" value="myfield2">
  <label for="myfield2"><span id="text_myfield2">Myfield2</span></label>

  <!-- 自动补全模块 -->
  <div class="autocomplete" style="width:300px;">
    <input id="myInput" type="text" placeholder="选择国家">
    <!-- 隐藏字段:存储选中项的id、value、label -->
    <input type="hidden" name="selected_id" id="selected_id">
    <input type="hidden" name="selected_value" id="selected_value">
    <input type="hidden" name="selected_label" id="selected_label">
  </div>

  <button id="button-filtra">筛选</button>    
  <input type="hidden" value="inputfilter" class="submit" id="button-filter" name="action">
</form>

2. 修改后的自动补全JavaScript代码

适配多字段对象数组,点击选项时同步更新隐藏字段的值:

function autocomplete(inp, arr) {
  var currentFocus;
  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++) {
        // 匹配对象的label字段
        if (arr[i].label.substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          b = document.createElement("DIV");
          // 高亮匹配的label文本
          b.innerHTML = "<strong>" + arr[i].label.substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].label.substr(val.length);
          // 存储当前对象的完整数据
          b.dataset.item = JSON.stringify(arr[i]);
          // 点击选项时更新输入框和隐藏字段
          b.addEventListener("click", function(e) {
              var selectedItem = JSON.parse(this.dataset.item);
              inp.value = selectedItem.label;
              document.getElementById('selected_id').value = selectedItem.id;
              document.getElementById('selected_value').value = selectedItem.value;
              document.getElementById('selected_label').value = selectedItem.label;
              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 countries = [
  {label: "Afghanistan", value: 100, id: 1},
  {label: "Albania", value: 101, id: 2},
  {label: "Algeria", value: 102, id: 3},
  // 可继续添加更多对象
];

// 初始化自动补全
autocomplete(document.getElementById("myInput"), countries);

3. PHP端接收数据

在AJAX处理逻辑中,获取自动补全选中的字段值:

// 接收原有复选框字段
if(isset($_POST['myfield1'])) {
    $myfield1 = $_POST['myfield1'];
}
if(isset($_POST['myfield2'])) {
    $myfield2 = $_POST['myfield2'];
}

// 接收自动补全选中的字段
$selected_id = isset($_POST['selected_id']) ? $_POST['selected_id'] : '';
$selected_value = isset($_POST['selected_value']) ? $_POST['selected_value'] : '';
$selected_label = isset($_POST['selected_label']) ? $_POST['selected_label'] : '';

// 后续可根据业务需求使用这些值
// 示例:echo "选中国家ID:{$selected_id},值:{$selected_value},名称:{$selected_label}";

4. 原有AJAX提交代码(无需修改)

原AJAX代码会自动序列化所有表单字段(包括新增的隐藏字段):

jQuery(function($){     
  $(document).on("submit", "form#filter", function(e) {
    e.preventDefault();
    var filter = $('#filter');
    $.ajax({
        url:filter.attr('action'),
        data:filter.serialize(), // 自动包含所有表单字段
        type:filter.attr('method'),
        beforeSend:function(xhr){
            filter.find('button').text('筛选中...');
        },
        success:function(data){
            filter.find('button').text('筛选');
            $('#response').html(data);
        }
    });
    return false;   
  });
});  

内容的提问来源于stack exchange,提问作者James

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 06:45:56