Lvkz
Lvkz

Reputation: 966

Select2 on elements loaded with JQuery

I'm using select2 on a project, and is working as it should, initiating the select2 using:

$(function() {
  $(".elegible").select2();
});

The issue comes in when I'm trying to call de function to elements loaded by JQuery, I don't know how to call that function. I've tried "on" but it does not load the selects with the select2. The only thing I found is this:

$(document).ajaxComplete(function(e, xhr, settings){
    $(".elegible").select2();
});

But this calls that function every time an ajax call is completed, even in those cases when I'm not needing the select2. My question is: How can I call the select to on elements loaded later? Is the method that I'm using right now valid? Can I improve that?

Thanks!

Adding Info: I call the new content by getting it from another page - which loads the select - using ajax:

$.get('detalle_miembro/' + this.id)
  .done(function(result) {
    $('#detalle_miembro').html(result);
  });

And placing it, in a div: <div id="detalle_miembro"></div>

Upvotes: 0

Views: 213

Answers (1)

PeterKA
PeterKA

Reputation: 24638

Here is how you can call select on just the new content added:

$.get('detalle_miembro/' + this.id).done(function(result) {
    $('#detalle_miembro').html(result).find(".elegible").select2();
});

Upvotes: 1

Related Questions