Jquery | Ciprian Dobrea

Archive for category JQuery

How to disable specific options in JQuery Autocomplete lists

If you ever had to disable autocomplete results while using JQuery Autocomplete, here is the method I found most useful:



First, mark your entries as disabled server-side, before you send it as json

01
02
$items = array(); // add your items here
03
 
04
$items[] = array(
05
  'id' => $i,
06
  'label' => '<strong>This option is disabled</strong><br/>Too many results, be more specific',
07
  'value' => 'disabled' // this will specify what we disable
08
);
09
 
10
die(json_encode($items));
11

Then simply add them as non-autocomplete items in the autocomplete list, while at the same time enabling html code in items:

01
02
$('#autocomplete_polita').autocomplete({
03
  source : webRoot + 'ajax/my_autocomplete',
04
}).data("autocomplete")._renderItem = function(ul, item) {
05
  if(item.value=='0'){
06
    return $('<li class="ui-menu-item disabled"></li>').data("item.autocomplete", item).append('<span>'+item.label+'</span>').appendTo(ul);
07
  }else{
08
    return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "</a>").appendTo(ul);
09
  }
10
};
11

Then style this no-option as one (maybe using disabled-style colors:

01
02
li.ui-menu-item.disabled{
03
  text-decoration: none;
04
  display: block;
05
  padding: .2em .4em;
06
  line-height: 1.5;
07
  zoom: 1;
08
  color: #CCC;
09
}
10

, , , , ,

1 Comment