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

如何实现光标离开#select-or-enter-category时校验输入并显示指定警告?

实现输入框失焦时校验内容是否在Typeahead下拉列表中的逻辑

我来帮你把校验逻辑和现有代码结合起来,实现你要的功能。咱们一步步来:


第一步:调整警告元素的默认状态

首先,你的警告消息默认应该是隐藏的,只有在校验不通过时才显示。给你的警告元素加一个hidden类,同时定义对应的CSS:

修改后的警告HTML:

<div class="row clearfix">
  <div class="col-sm-8 col-sm-offset-2">
    <div>
      <div class="form-line focus">
        <span class="category-status hidden" style="color: red;">
          This entered category is not found in the category list.<br>
          Press button on the right to save this new category.
        </span>
      </div>
    </div>
  </div>
</div>

添加隐藏样式:

.hidden {
  display: none;
}

第二步:编写失焦校验逻辑

接下来,我们需要监听输入框的blur事件(光标离开时触发),检查输入内容是否存在于Typeahead的下拉数据源中。这里分两种适配场景:

场景1:原生JavaScript实现

假设你的Typeahead数据源是本地数组(如果是远程数据源,需要调整为接口校验逻辑):

// 替换成你实际的Typeahead下拉选项数组
const categoryOptions = ['JavaScript', 'Python', 'Java', 'CSS', 'UI/UX'];

// 获取DOM元素
const categoryInput = document.getElementById('select-or-enter-category');
const statusElement = document.querySelector('.category-status');
const catIdInput = document.getElementById('cat-id');

// 监听失焦事件
categoryInput.addEventListener('blur', function() {
  const inputValue = this.value.trim();
  
  // 输入为空时,直接隐藏警告并清空分类ID
  if (!inputValue) {
    statusElement.classList.add('hidden');
    catIdInput.value = '';
    return;
  }
  
  // 校验输入值是否在下拉列表中(不区分大小写)
  const isCategoryExists = categoryOptions.some(option => 
    option.toLowerCase() === inputValue.toLowerCase()
  );
  
  if (!isCategoryExists) {
    // 不在列表中,显示警告
    statusElement.classList.remove('hidden');
    catIdInput.value = ''; // 清空隐藏域,因为不是已存在的分类
  } else {
    // 在列表中,隐藏警告,并设置对应的分类ID(如果需要)
    statusElement.classList.add('hidden');
    // 这里可以根据分类名获取对应ID,比如调用你自己的方法:
    // catIdInput.value = getCategoryIdByValue(inputValue);
  }
});

// 额外优化:监听Typeahead选中事件,选中后自动隐藏警告
categoryInput.addEventListener('typeahead:selected', function(event, selection) {
  statusElement.classList.add('hidden');
  // 设置选中分类的ID
  // catIdInput.value = selection.id;
});

场景2:jQuery版本(适配你的data-provide="typeahead")

如果你的项目用了jQuery和Bootstrap Typeahead,代码可以这样写:

// 替换成你实际的Typeahead数据源
var categoryOptions = ['JavaScript', 'Python', 'Java', 'CSS', 'UI/UX'];

// 初始化Typeahead并绑定事件
$('#select-or-enter-category')
  .typeahead({ source: categoryOptions })
  .on('blur', function() {
    const inputVal = $(this).val().trim();
    const $status = $('.category-status');
    const $catId = $('#cat-id');
    
    if (!inputVal) {
      $status.addClass('hidden');
      $catId.val('');
      return;
    }
    
    const exists = categoryOptions.some(opt => 
      opt.toLowerCase() === inputVal.toLowerCase()
    );
    
    if (!exists) {
      $status.removeClass('hidden');
      $catId.val('');
    } else {
      $status.addClass('hidden');
      // 设置分类ID:$catId.val(getCategoryId(inputVal));
    }
  })
  // 选中下拉选项时自动隐藏警告
  .on('typeahead:selected', function(event, selection) {
    $('.category-status').addClass('hidden');
    // $('#cat-id').val(selection.id);
  });

关键注意点

  • 数据源同步:如果你的Typeahead数据源是动态加载的(比如从AJAX获取),一定要确保数据源加载完成后再绑定blur事件,否则校验会失效。
  • 大小写敏感:上面的代码用了不区分大小写的校验,如果你需要严格区分,去掉.toLowerCase()即可。
  • 分类ID同步:当用户选中下拉选项时,记得同步更新隐藏域#cat-id的值,这样表单提交时能正确传递已存在分类的ID。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:14:20