简体   繁体   中英

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);
};

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM