Hello,

If there is an element on the page to which the jQuery plugin binds (for example, select2), then the plugin works. If an element is created by a script, then the plugin is not bound to it. How to connect plugins to dynamically created elements? (In the example, clicking on the "add select" button creates a new drop-down list, but the plugin is not connected to it)

$(document).ready(function() { $("select").select2(); $("input[type=button]").on('click',function(){ $("div").append('<select><option>1</option><option>2</option><option>3</option><option>4</option></select>'); }); }); 
 <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script> <div> <input type="button" value="Add select"/> <br/> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> </div> 

    1 answer 1

    well, then execute the plugin for the newly created element (the div selector is slightly too general by the way, do something about it)

     $(document).ready(function() { $("select").select2(); $("input[type=button]").on('click',function(){ $('<select><option>1</option><option>2</option><option>3</option><option>4</option></select>') .appendTo('div').select2(); }); }); 
     <link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" /> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script> <div> <input type="button" value="Add select"/> <br/> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> <select> <option>1</option> <option>2</option> <option>3</option> <option>4</option> </select> </div> 

    • The selector div is for example only, there it’s one :) Are there ways to do it differently? I have a lot of other markup code (AJAX) along with select. I am looking for something like $(docunent).on('change' function(){...}); to write once and with all the changes the plugin connected to select - atom-22
    • no, i.e. but there is a brake (watch out for the DOM brake, and it doesn’t work everywhere), do approximately $(<div><select></select></div>).appendTo(myPlace).find('select').select2() - zb '
    • I tried .bind("DOMSubtreeModified",function(){}); This is really bad (chrome thought for a long time and crashed the page). Thank you, I will do something in your style - atom-22