【问题标题】:Disable an option in jQuery Autocomplete?禁用 jQuery 自动完成中的选项?
【发布时间】:2020-11-30 23:46:12
【问题描述】:

我正在使用以下 jquery 从 php 脚本返回的值创建一个自动完成菜单。

这些是 PHP 返回的值。

["Site 4","Site 2","Site 1","*************","Site 6","Site 7","Site 0"]

这是我的自动完成jQuery:

$( '#site' ).autocomplete({
    source: 'siteCheck.php',
    autoFocus: true, 
    minLength: 1,
    select: function( event, ui ) {
        $('#site').val(ui);
    }
}); 

这会将正确的结果返回到屏幕并显示************* 选项。但是,我想将该选项设置为 BOLD 并停止从列表中选择它。

这可能吗?我曾尝试使用 jquery 禁用选择选项,但这似乎没有任何作用。

这不是另一张票的重复,他们询问如何在显示特定数量的结果后禁用条目。我想禁用一个特定条目。

【问题讨论】:

    标签: javascript jquery jquery-ui-autocomplete


    【解决方案1】:

    我在 jQuery 的官方网站上修改了one the examples。它应该足够简单以适应您的数据。

    它是这样工作的:

    1. 数据数组 (projects) 中的属性 disabled 告诉自定义渲染逻辑是否禁用某个选项。

    2. 如果元素将disabled 设置为true,我已自定义渲染器以在选项上设置类ui-state-disabled。它还有助于将background-color 设置为灰色,将font-weight 设置为粗体。

    3. 然后在 focus 事件处理程序上,如果该项目被禁用,则 return false。这可以防止 jQuery 在您向下导航时将项目填充到输入中。

    4. 最后,在 select 处理程序上,再次防止根据 disabled 属性的值选择值。

    var projects = [{
        value: "jquery",
        label: "jQuery",
        desc: "the write less, do more, JavaScript library",
        icon: "jquery_32x32.png",
        disabled: false
      },
      {
        value: "jquery-ui",
        label: "jQuery UI",
        desc: "the official user interface library for jQuery",
        icon: "jqueryui_32x32.png",
        disabled: true
      },
      {
        value: "sizzlejs",
        label: "Sizzle JS",
        desc: "a pure-JavaScript CSS selector engine",
        icon: "sizzlejs_32x32.png",
        disabled: false
      }
    ];
    
    
    $("#project").autocomplete({
        minLength: 0,
        source: projects,
        focus: function(event, ui) {
          if(ui.item.disabled) {
            console.log("Preventing focus.");
            return false;
          } else {
            return true;
          }
        },
        select: function(event, ui) {
          if(!ui.item.disabled) {
            $("#project").val(ui.item.label);
          } else {
            console.log("Preventing selection.");
          }
          return false;
        }
      })
      .autocomplete("instance")._renderItem = function(ul, item) {
        return $("<li>")
          .append("<div class='"+(item.disabled ? 'ui-state-disabled' : '')+"'>" + item.label + "<br>" + item.desc + "</div>")
          .appendTo(ul);
      };
    .ui-menu-item-wrapper.ui-state-disabled {
      background-color: #aaa;
      font-weight: bold;
    }
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    
    <input id="project">

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2019-07-02
      • 1970-01-01
      • 2012-10-14
      • 2020-11-24
      • 2020-05-01
      • 2011-09-05
      相关资源
      最近更新 更多