Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to check if an element has jquery select2 already applied to it?

I want to apply select2 to a bunch of jquery elements on the page that all have the same class name but it looks like if i call select2() on an element that already has had a select2() called on it then it blows up. here is my code

 $('.MyDropdowns').each(function (i, obj) {     $(obj).select2({ width: "455px" }); }); 

so I want something like:

 $('.MyDripdowns').each(function (i, obj) {     if (!$(obj).HasSelect2Initiatized)     {         $(obj).select2({ width: "455px" });     } }); 

Does anything like this exist?

like image 653
leora Avatar asked Apr 24 '15 17:04

leora


People also ask

How do I know if Select2 is open?

select2:open is fired whenever the dropdown is opened. select2:opening is fired before this and can be prevented. select2:close is fired whenever the dropdown is closed. select2:closing is fired before this and can be prevented.

Is Select2 jQuery?

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

How do I clean my Select2?

In order to clear the selection of those values which are selected using a Select2 drop down,we can use the empty() function. The dropdown can be reset using Jquery. $("#select2_example"). empty();


2 Answers

you can check if the element has select2 attribute

$('.MyDripdowns').each(function (i, obj) {     if (!$(obj).data('select2'))     {         $(obj).select2({ width: "455px" });     } }); 

EDIT

As @Fr0zenFyr said in his comment for v4.0 you can use :

if (!$(obj).hasClass("select2-hidden-accessible"))

like image 82
semirturgay Avatar answered Sep 29 '22 16:09

semirturgay


Working solution:

$('.MyDripdowns:not([class^="select2"])').each(function (i, obj) {     $(obj).select2({width: "455px"}); }) 

Links:

  1. ^= attribute starts with selector
  2. :not selector
like image 33
userlond Avatar answered Sep 29 '22 17:09

userlond