chosen.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /**
  2. * @file
  3. * Attaches behaviors for the Chosen module.
  4. */
  5. (function($) {
  6. Drupal.behaviors.chosen = {
  7. attach: function(context, settings) {
  8. settings.chosen = settings.chosen || Drupal.settings.chosen;
  9. // Prepare selector and add unwantend selectors.
  10. var selector = settings.chosen.selector;
  11. // Function to prepare all the options together for the chosen() call.
  12. var getElementOptions = function (element) {
  13. var options = $.extend({}, settings.chosen.options);
  14. // The width default option is considered the minimum width, so this
  15. // must be evaluated for every option.
  16. if (settings.chosen.minimum_width > 0) {
  17. if ($(element).width() < settings.chosen.minimum_width) {
  18. options.width = settings.chosen.minimum_width + 'px';
  19. }
  20. else {
  21. options.width = $(element).width() + 'px';
  22. }
  23. }
  24. // Some field widgets have cardinality, so we must respect that.
  25. // @see chosen_pre_render_select()
  26. if ($(element).attr('multiple') && $(element).data('cardinality')) {
  27. options.max_selected_options = $(element).data('cardinality');
  28. }
  29. return options;
  30. };
  31. // Process elements that have opted-in for Chosen.
  32. // @todo Remove support for the deprecated chosen-widget class.
  33. $('select.chosen-enable, select.chosen-widget', context).once('chosen', function() {
  34. options = getElementOptions(this);
  35. $(this).chosen(options);
  36. });
  37. $(selector, context)
  38. // Disabled on:
  39. // - Field UI
  40. // - WYSIWYG elements
  41. // - Tabledrag weights
  42. // - Elements that have opted-out of Chosen
  43. // - Elements already processed by Chosen.
  44. .not('#field-ui-field-overview-form select, #field-ui-display-overview-form select, .wysiwyg, .draggable select[name$="[weight]"], .draggable select[name$="[position]"], .chosen-disable, .chosen-processed')
  45. .filter(function() {
  46. // Filter out select widgets that do not meet the minimum number of
  47. // options.
  48. var minOptions = $(this).attr('multiple') ? settings.chosen.minimum_multiple : settings.chosen.minimum_single;
  49. if (!minOptions) {
  50. // Zero value means no minimum.
  51. return true;
  52. }
  53. else {
  54. return $(this).find('option').length >= minOptions;
  55. }
  56. })
  57. .once('chosen', function() {
  58. options = getElementOptions(this);
  59. $(this).chosen(options);
  60. });
  61. }
  62. };
  63. })(jQuery);