How to make Select2 work with jQuery Form Repeater?

How to make Select2 work with jQuery Form Repeater?

What are jQuery form repeater and Select2?

If you have ever had to create an HTML form with a variable number of inputs then I am sure you came across a plugin called jQuery form repeater. This plugin is a really handy tool as it enables you to duplicate any sort of input in a Form with a click of a button!. I have used this plugin in many of my projects and it has worked fine for me but except for a single case of another jQuery plugin called Select2. Just like form repeater Select2 is another awesome jQuery plugin which gives you a customizable select box with support for searching, remote data sets, tagging, infinite scrolling and many other useful options. But it has been a long-standing problem for many developers to make Select2 work with jQuery form repeater.

The problem:

It’s all in the way both these plugins work by default. The Form Repeater duplicates the specified input on a button click but Select2 must be manually initialized using jQuery and is usually initialized on document ready.

The problem arises when you try to duplicate a Select2 field. It does not work because the Select2 is not initialized for the newly duplicated input!. So let us see the workaround to make Select2 work with Form Repeater.

Make Select2 work with jQuery form repeater:

Here is a solution I came up with which involves initializing Select2 on form repeater button click!

A typical jQuery form repeater example:

Notice I have assigned an id="repeater-button" button which triggers the form repeater? We will hook into this button’s click event and execute a jQuery function which will initialize the Select2 for all the inputs with class="select2"

Now just put this script after the body tag:

If you execute the above function on button click event it assures that the function is only executed after the inputs have been duplicated and waiting for just 100 milliseconds also guarantees that the input has already been duplicated.

Your Select2 should work now with form repeater!! but just make sure you initialize the original select2 input on document ready!

What do you think? Is there a better way of doing this? Share your thoughts in the comments below!!

Did you like this article? then consider checking out my posts in the web development category and my projects!

Leave a Reply

4 Comments on "How to make Select2 work with jQuery Form Repeater?"

avatar
  Subscribe  
newest oldest most voted
Notify of
kidane gebremedhin
Guest

Very helpful and clear. Great!

Nelson
Guest
Nelson

did you try this on a real example? Is not working in my project.