説明なし

jquery.grp_related_m2m.js 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * GRAPPELLI RELATED M2M
  3. * m2m lookup
  4. */
  5. (function($){
  6. var methods = {
  7. init: function(options) {
  8. options = $.extend({}, $.fn.grp_related_m2m.defaults, options);
  9. return this.each(function() {
  10. var $this = $(this);
  11. // add placeholder
  12. $this.parent().find('a.related-lookup').after(options.placeholder);
  13. // change lookup class
  14. $this.next().addClass("grp-m2m");
  15. // add related class
  16. $this.addClass('grp-has-related-lookup');
  17. // lookup
  18. lookup_id($this, options); // lookup when loading page
  19. $this.on("change focus keyup", function() { // id-handler
  20. lookup_id($this, options);
  21. });
  22. });
  23. }
  24. };
  25. $.fn.grp_related_m2m = function(method) {
  26. if (methods[method]) {
  27. return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  28. } else if (typeof method === 'object' || ! method) {
  29. return methods.init.apply(this, arguments);
  30. } else {
  31. $.error('Method ' + method + ' does not exist on jQuery.grp_related_m2m');
  32. }
  33. return false;
  34. };
  35. var lookup_id = function(elem, options) {
  36. $.getJSON(options.lookup_url, {
  37. object_id: elem.val(),
  38. app_label: grappelli.get_app_label(elem),
  39. model_name: grappelli.get_model_name(elem),
  40. query_string: grappelli.get_query_string(elem)
  41. }, function(data) {
  42. values = $.map(data, function (a, i) {
  43. if (data.length === i + 1 && !a.safe) {
  44. return $('<span class="grp-placeholder-label"></span>').text(a.label + '\u200E');
  45. } else if (data.length === i + 1 && a.safe) {
  46. return $('<span class="grp-placeholder-label"></span>').html(a.label + '\u200E');
  47. } else if (a.safe) {
  48. return $('<span class="grp-placeholder-label"></span>').html(a.label + '\u200E').append($('<span class="grp-separator"></span>'));
  49. } else {
  50. return $('<span class="grp-placeholder-label"></span>').text(a.label + '\u200E').append($('<span class="grp-separator"></span>'));
  51. }
  52. });
  53. if (values === "") {
  54. elem.parent().find('.grp-placeholder-related-m2m').hide();
  55. } else {
  56. elem.parent().find('.grp-placeholder-related-m2m').show();
  57. }
  58. elem.parent().find('.grp-placeholder-related-m2m').html(values);
  59. });
  60. };
  61. $.fn.grp_related_m2m.defaults = {
  62. placeholder: '<div class="grp-placeholder-related-m2m"></div>',
  63. repr_max_length: 30,
  64. lookup_url: ''
  65. };
  66. })(grp.jQuery);