jQuery UI AutoComplete: Only allow selected valued from suggested list

I got the same problem with selected not being defined. Got a work-around for it and added the toLowerCase function, just to be safe.

$('#' + specificInput).autocomplete({ 
  create: function () {
    $(this).data('ui-autocomplete')._renderItem = function (ul, item) {
      $(ul).addClass('for_' + specificInput); //usefull for multiple autocomplete fields
      return $('<li data-id = "' + item.id + '">' + item.value + '</li>').appendTo(ul); 
    };
  }, 
  change:
    function( event, ui ){
      var selfInput = $(this); //stores the input field
      if ( !ui.item ) { 
        var writtenItem = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val().toLowerCase()) + "$", "i"), valid = false;

        $('ul.for_' + specificInput).children("li").each(function() {
          if($(this).text().toLowerCase().match(writtenItem)) {
            this.selected = valid = true;
            selfInput.val($(this).text()); // shows the item's name from the autocomplete
            selfInput.next('span').text('(Existing)');
            selfInput.data('id', $(this).data('id'));
            return false;
          }
        });

        if (!valid) { 
          selfInput.next('span').text('(New)');
          selfInput.data('id', -1); 
        }
    }
}

http://jsfiddle.net/pxfunc/j3AN7/

var validOptions = ["Bold", "Normal", "Default", "100", "200"]
previousValue = "";

$('#ac').autocomplete({
    autoFocus: true,
    source: validOptions
}).keyup(function() {
    var isValid = false;
    for (i in validOptions) {
        if (validOptions[i].toLowerCase().match(this.value.toLowerCase())) {
            isValid = true;
        }
    }
    if (!isValid) {
        this.value = previousValue
    } else {
        previousValue = this.value;
    }
});

You could also use this:

change: function(event,ui){
  $(this).val((ui.item ? ui.item.id : ""));
}

The only drawback I've seen to this is that even if the user enters the full value of an acceptable item, when they move focus from the textfield it will delete the value and they'll have to do it again. The only way they'd be able to enter a value is by selecting it from the list.

Don't know if that matters to you or not.