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

Tom Select默认create:true异常,配置create:false与no_add插件无效求助

问题:Tom Select 始终允许创建新项,配置 create: false 无效

技术栈:Rails 7、Bootstrap 5、Tom Select ^2.3.1

Tom Select 官方文档标注 create 参数默认值为 false,但实际使用中默认开启创建新项功能。手动设置 create: false 后无效果,启用 no_add 插件也无法阻止,检查页面元素时始终显示创建提示(如 <div class="create active" data-selectable="" aria-selected="true">Add <strong>asdf</strong>…</div>),需求是完全禁止用户通过下拉菜单创建新项。


相关代码

Package.json

{
  "name": "app",
  "private": "true",
  "dependencies": {
    "@hotwired/stimulus": "^3.2.1",
    "@hotwired/turbo-rails": "^7.3.0",
    "@popperjs/core": "^2.11.6",
    "bootstrap": "^5.2.3",
    "bootstrap-icons": "^1.10.3",
    "esbuild": "^0.17.10",
    "sass": "^1.58.3",
    "tom-select": "^2.3.1"
  },
  "scripts": {
    "build": "esbuild app/javascript/*.* --bundle --sourcemap --outdir=app/assets/builds --public-path=assets",
    "build:css": "sass ./app/assets/stylesheets/application.bootstrap.scss:./app/assets/builds/application.css --no-source-map --load-path=node_modules"
  }
}

search_controller.js

import { Controller } from "@hotwired/stimulus"
import TomSelect from "tom-select"

// Connects to data-controller="search"
export default class extends Controller {

  // static targets = ["input", "suggestions"];

  connect() { 
    console.log("YES search controller working - connect method called", this.element);
    new TomSelect(this.element, {
      //Uncomment below and change create to true to allow user to add new entries from forms
      //createOnBlur: true,
      create: false,
      plugins: ['no_add']
    });
    // document.addEventListener("click", (event) => { // <-- Corrected syntax
    //   if (!this.element.contains(event.target)) {
    //     this.hideSuggestions();
    //   }
    // });
  }

  
  suggestions() {
    console.log("Suggestion Function Running");
    const query = this.inputTarget.value;
    const url = this.element.dataset.suggestionsUrl;

    clearTimeout(this.setTimeout)

    this.timeout = setTimeout(()=> {
      this.requestSuggestions(query,url);
    }, 250);
  }

  requestSuggestions(query, url) {
    if (query.length === 0) {
      this.hideSuggestions();
      return;
    }
    
    this.showSuggestions();
    
    fetch (url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-CSRF-Token": document.querySelector("meta[name='csrf-token']").content
      },
        body: JSON.stringify ({query: query}),
    }).then(response => {
      response.text().then( html => {
        document.body.insertAdjacentHTML("beforehand", "html");
      })
    })
  }

  hideSuggestions() {
    if (!this.childWasClicked) {
      this.suggestionsTarget.classList.add("hidden");
    }
    this.childWasClicked = false;
  }

  showSuggestions() {
    this.suggestionsTarget.classList.remove("hidden");
  }

}

Rails 表单代码

<h4>With Whom?</h4>

<%= form.select :contact_id, @contacts.map{|c| ["#{c.first_name} #{c.last_name}", c.id]}, 
  {prompt: 'With whom did you have this Interaction?'},
  class: 'autocomplete-form',
  data: {
    controller: 'search',
    oldaction: 'keyup->search#suggestions',
    suggestions_url: search_suggestions_path, search_target: "input"
        } %>

<span>Need to <%= link_to "add a new contact", new_contact_path, target: "_blank" %>?</span>
</div>

解决方法

1. 避免重复初始化 Tom Select

页面可能存在多次初始化 Tom Select 的情况,导致配置被覆盖。初始化前先销毁已有实例:

connect() { 
  console.log("YES search controller working - connect method called", this.element);
  // 销毁已存在的TomSelect实例
  if (this.element.tomselect) {
    this.element.tomselect.destroy();
  }
  new TomSelect(this.element, {
    create: false,
    plugins: ['no_add']
  });
}

2. 完整禁用创建相关配置

除了 create: false,额外添加 createOnBlur 和 persist 配置,彻底关闭创建行为:

new TomSelect(this.element, {
  create: false,
  createOnBlur: false,
  persist: false,
  plugins: ['no_add']
});

3. 检查表单元素属性

确认 Rails 生成的 select 元素没有 multiple 等特殊属性,这类属性可能干扰 Tom Select 的配置逻辑。

4. CSS 强制隐藏创建项

如果以上方法均无效,通过 CSS 直接隐藏创建提示元素:

.ts-dropdown .create {
  display: none !important;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 19:17:12