Dan Leveille
Dan Leveille

Reputation: 3210

How to override user input on Jquery autocomplete?

I have a simple autocomplete function that searches an array of objects. It's working fine, but I want to override what the user is searching for.

I want to append another input's value to their search. For example, if they search "cat", I want to append $('#input2').val() so their search becomes "cat dog" (without changing the actual <input>'s value).

This seems like an easy thing to do, but I can't figure out how to do it without overriding the entire search method.

Existing code:

$("#search").autocomplete({
    source: data,
    appendTo: '#admin-results'
}).data("ui-autocomplete")._renderItem = function(ul, item) {
  return $('<li>')
  .append('<div>' + item.label + '</div>')
  .appendTo(ul);
};

Upvotes: 0

Views: 473

Answers (2)

charlietfl
charlietfl

Reputation: 171690

The following will do what you ask by using function for source

var terms = ["c++", "java dog", "php dog", "coldfusion", "javascript dog", "asp dog", "ruby"]
$("#autocomplete").autocomplete({
  source: function(req, response) {
    var term = req.term + ' dog';// adjust to a dom value or whatever
    var res = terms.filter(function(item) {
      return item.toLowerCase() === term.toLowerCase()
    });
    response(res);
  }
});

Adjust filter function accordingly also. This is only rough for absolute match

DEMO

Upvotes: 2

techfang
techfang

Reputation: 97

1.get the val from #admin-results. put the val into a variable "a".
2.a = a + desiredVal
3.put the new "a" into #admin-results

Upvotes: 0

Related Questions