2017-09-24 70 views
0

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

这些是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禁用选择选项,但似乎没有做任何事情。

这不是其他票的复制品,他们要求如何在特定数量的结果显示后禁用条目..我想禁用ONE特定条目。

回答

1

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

下面是它如何工作的:

  1. 酒店disabled数据阵列(projects)告诉定制呈现逻辑的选项是否是禁用的。

  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">