Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i bind jquery select2 to new added selects?

i have a razor-mvc web and a couple of select's on a form. I bind this selects with the select2 plugin in jquery like this:

$('select.company_select, select.positions_select').select2();

And my form is an ajax form (ajax by javascript, not by Ajax.BeginForm). The thing is that when i submit the form, i add another form with the submited values of the first form, but the select's on that new form wont apply the select2 plugin. I know that this is normal because the new item and should be binded with .on() or .live() but i dont know how to do it.

Can you help me with it?

like image 879
Phoenix_uy Avatar asked Apr 17 '13 17:04

Phoenix_uy


2 Answers

use ajaxcomplete

$( document ).ajaxComplete(function(){
  $(".select2").select2();
});
like image 161
altkatz Avatar answered Sep 22 '22 13:09

altkatz


You are doing ajax call so make sure you re-init the select on whatever other selects you want in complete for any new select boxes on the page..

so your ajax call will look something like

$.ajax({ 
     url: '.../', 
     data..., 
     type...,
     success: function(data) 
     {
         $('#newFormAddedID select').select2();
     }

Should do the trick.. you can also do it in complete:function(... if the form gets added regardless of wether the ajax call is successful or not.

like image 37
JF it Avatar answered Sep 22 '22 13:09

JF it