-
Notifications
You must be signed in to change notification settings - Fork 364
/
Copy pathautocomplete-rails.js
16 lines (16 loc) · 2.64 KB
/
autocomplete-rails.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
* Unobtrusive autocomplete
*
* To use it, you just have to include the HTML attribute autocomplete
* with the autocomplete URL as the value
*
* Example:
* <input type="text" data-autocomplete="/url/to/autocomplete">
*
* Optionally, you can use a jQuery selector to specify a field that can
* be updated with the element id whenever you find a matching value
*
* Example:
* <input type="text" data-autocomplete="/url/to/autocomplete" data-id-element="#id_field">
*/
(function(e){var t=null;e.fn.railsAutocomplete=function(){var t=function(){if(!this.railsAutoCompleter){this.railsAutoCompleter=new e.railsAutocomplete(this)}};if(e.fn.on!==undefined){return $(document).on("focus",this.selector,t)}else{return this.live("focus",t)}};e.railsAutocomplete=function(e){_e=e;this.init(_e)};e.railsAutocomplete.fn=e.railsAutocomplete.prototype={railsAutocomplete:"0.0.1"};e.railsAutocomplete.fn.extend=e.railsAutocomplete.extend=e.extend;e.railsAutocomplete.fn.extend({init:function(t){function n(e){return e.split(t.delimiter)}function r(e){return n(e).pop().replace(/^\s+/,"")}t.delimiter=e(t).attr("data-delimiter")||null;t.noMatchesLabel=e(t).attr("data-no-matches-label")||"no existing match";e(t).autocomplete({source:function(n,i){e.getJSON(e(t).attr("data-autocomplete"),{term:r(n.term)},function(){if(arguments[0].length==0){arguments[0]=[];arguments[0][0]={id:"",label:t.noMatchesLabel}}e(arguments[0]).each(function(n,r){var i={};i[r.id]=r;e(t).data(i)});i.apply(null,arguments)})},change:function(t,n){if(e(e(this).attr("data-id-element")).val()==""){return}e(e(this).attr("data-id-element")).val(n.item?n.item.id:"");var r=e.parseJSON(e(this).attr("data-update-elements"));var i=n.item?e(this).data(n.item.id.toString()):{};if(r&&e(r["id"]).val()==""){return}for(var s in r){e(r[s]).val(n.item?i[s]:"")}},search:function(){var e=r(this.value);if(e.length<2){return false}},focus:function(){return false},select:function(r,i){if(i.item.value!=t.noMatchesLabel){var s=n(this.value);s.pop();s.push(i.item.value);if(t.delimiter!=null){s.push("");this.value=s.join(t.delimiter)}else{this.value=s.join("");if(e(this).attr("data-id-element")){e(e(this).attr("data-id-element")).val(i.item.id)}if(e(this).attr("data-update-elements")){var o=e(this).data(i.item.id.toString());var u=e.parseJSON(e(this).attr("data-update-elements"));for(var a in u){e(u[a]).val(o[a])}}}var f=this.value;e(this).bind("keyup.clearId",function(){if(e(this).val().trim()!=f.trim()){e(e(this).attr("data-id-element")).val("");e(this).unbind("keyup.clearId")}});e(t).trigger("railsAutocomplete.select",i)}return false}})}});e(document).ready(function(){e("input[data-autocomplete]").railsAutocomplete()})})(jQuery);