diff --git a/CHANGELOG.md b/CHANGELOG.md index dcd83ce..71139ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,10 @@ Changelog Summary ================= +### v5.3.0 +* Added djangoSelect2 jQuery plugin to support + dynamic field initialisation + ### v5.2.0 * Added pagination diff --git a/django_select2/__init__.py b/django_select2/__init__.py index 46f7cf6..b99e38f 100644 --- a/django_select2/__init__.py +++ b/django_select2/__init__.py @@ -9,4 +9,4 @@ The app includes Select2 driven Django Widgets and Form Fields. """ -__version__ = "5.2.1" +__version__ = "5.3.0" diff --git a/django_select2/static/django_select2/django_select2.js b/django_select2/static/django_select2/django_select2.js index c20b374..1198681 100644 --- a/django_select2/static/django_select2/django_select2.js +++ b/django_select2/static/django_select2/django_select2.js @@ -1,15 +1,19 @@ -$(function () { - $('.django-select2').not('django-select2-heavy').select2(); - $('.django-select2.django-select2-heavy').each(function () { - var field_id = $(this).data('field_id'); - $(this).select2({ +(function ($) { + + var init = function ($el, options) { + $el.select2(options); + return $el; + }; + + var initHeavy = function ($el, options) { + var settings = $.extend({ ajax: { data: function (params) { return { term: params.term, page: params.page, - field_id: field_id - } + field_id: $el.data('field_id') + }; }, processResults: function (data, page) { return { @@ -17,10 +21,26 @@ $(function () { pagination: { more: data.more } - } + }; } } - }); - }); -}); + }, options); + $el.select2(settings); + return $el; + }; + + $.fn.djangoSelect2 = function (options) { + var settings = $.extend({}, options); + var heavy = $(this).hasClass('django-select2-heavy'); + if (heavy) { + return initHeavy(this, settings); + } + return init(this, settings); + }; + + $(function () { + $('.django-select2').djangoSelect2(); + }); + +}(this.jQuery)); diff --git a/docs/django_select2.rst b/docs/django_select2.rst index 10244be..5f49614 100644 --- a/docs/django_select2.rst +++ b/docs/django_select2.rst @@ -40,3 +40,21 @@ Cache :members: :undoc-members: :show-inheritance: + + +JavaScript +---------- + +DjangoSelect2 handles the initialization of select2 fields automatically. Just include +``{{ form.media.js }}`` in your template before the closing ``body`` tag. That's it! + +If you insert forms after page load or if you want to handle the initialization +yourself, DjangoSelect2 provides a jQuery-Plugin. It will handle both normal and +heavy fields. Simply call ``djangoSelect2(options)`` on your select fields.:: + + $('.django-select2').djangoSelect2(); + + +You can pass see `Select2 options `_ if needed:: + + $('.django-select2').djangoSelect2({placeholder: 'Select an option'});