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

jQuery autocomplete输入框清空时如何重置关联hidden隐藏域值

解决方案

给可见输入框绑定失焦事件,检测到内容为空时主动清空关联隐藏域即可,修改后的完整代码如下:

$( function() {
 // Single Select
 $( "#locations" ).autocomplete({
  source: function( request, response ) {
   // Fetch data
   $.ajax({
    url: "getlocations.php",
    type: 'post',
    dataType: "json",
    data: {
     search: request.term
    },
    success: function( data ) {
     response( data );
    }
   });
  },
  select: function (event, ui) {
     // Set selection
     $('#locations').val(ui.item.label); // display the selected text
      $('#location').val(ui.item.value);
     return false;
  },
  focus: function(event, ui){
     $( "#locations" ).val( ui.item.label );
      $('#location').val(ui.item.value);
     return false;
   },
 });
 // 新增失焦监听逻辑
 $("#locations").on("blur", function() {
  // 去除首尾空格后判断是否为空
  if ($(this).val().trim() === "") {
    $("#location").val("");
  }
 });
});

补充说明

如果需要实现实时同步,不需要等待用户离开输入框就触发清空逻辑,可以把事件从blur换成input,用户修改输入框内容的瞬间就会执行判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:18:02