Select2() is not a function

JavascriptJqueryJquery Select2

Javascript Problem Overview


So i have downloaded select2 i have "installed it" by putting it into my folder and then loaded it on my site when i check the console (where i can see all of the scripts being loaded) i can see the file select2.js

I went to their documentation and copied it and added $("#e9").select2();

However when i load the page i get the following error:

TypeError: $(...).select2 is not a function
	

$("#e9").select2();

Have anyone else experianced anything like this?

Additional information here is my script:

    jQuery(document).ready(function(){
    var max_amount = parseFloat($('#max_amount').val());
    $( "#item_amount" ).keyup(function() {
           if($(this).val() > max_amount){
            $(this).val( max_amount);
        }
        if( /\D/.test($(this).val()) ){
            alert('Må kun indeholde tal!');
            $(this).val('');
        }
        if($(this).val()== '0'){
            alert('Må ikke være 0!');
            $(this).val('');
        }
    });
    $("#e1").select2();

});
function addToBasket(){
    var amount = $('#item_amount').val();
    if(amount == ""){
        amount = 1;
    }

    if(amount > 0){
    $.ajax({
        type: 'POST',
        url: myBaseUrl + 'Products/addItemToBasket',
        dataType: 'json',
        data: {
            id: window.location.pathname.substring(window.location.pathname.lastIndexOf('/') + 1),
            amount: amount
        },
        success: function (data) {
            var urlToBasket = myBaseUrl+'Products/basket';
            var newAmount = parseInt(amount)
            var price = data[0]['Product']['pris'];
            var id = data[0]['Product']['id'];
            var dat = data;
            var tmp_basket_html = $('#basket_amount').html();
           if($('#basket_amount').html() !== " Tom"){
              $('#shopping_table_body').append(
                  "<tr id='"+id+"'>" +
                      "<td class='image'>" +
                      ""+
                      "</td>" +
                      "<td class='name'>" +
                      " "+data[0]['Product']['name'] +
                      "</td>"+
                      "<td class='quantity'>" +
                      "x "+amount +""+
                      "</td>"+
                      "<td class='total'>" +
                      ""+price*amount+
                      "</td>" +
                      ""+
                      "<td class='remove'>" +
                      "<input class='icon-remove' type='button' onclick='removeItemFromBasket("+id+")'>"+
                      "</td>"+
                      "</tr>"
              );
           }else{
               $("#shopping_menu").append(
                   "<ul class='dropdown-menu topcartopen'>"+
                       "<li id='basket_list'>"+
                      "<table id='shopping_table'>"+
                        "<tbody id='shopping_table_body'>"+
                       "<tr id='"+id+"'>" +
                       "<td class='image'>" +
                       ""+
                       "</td>" +
                       "<td class='name'>" +
                       " "+data[0]['Product']['name'] +
                       "</td>"+
                       "<td class='quantity'>" +
                       "x "+amount +""+
                       "</td>"+
                       "<td class='total'>" +
                       ""+price*amount+
                       "</td>" +
                       ""+
                       "<td class='remove'>" +
                       "<input class='icon-remove' type='button' onclick='removeItemFromBasket("+id+")'>"+
                       "</td>"+
                       "</tr>"+
                       "</table>"+
                       "</li>"+
                       "<div class='well pull-right'>"+
                       "<input type='button' onclick='goToBasket()' class='btn btn-success' value='Tjek ud'>"+
                       "</div>"+
                       "</ul>"

               )
           }
            updateTotal(amount,price);
            updateBasketAmount();
        }
    });
    }
    Notifier.success('Vare tilføjet', 'Tilføjet'); // text and title are both optional.
}
function updateTotal(amount, price){
    var price = parseFloat(price);
    var oldValue = parseFloat($('#basket_total_cost').html());
    var newPrice = amount*price+oldValue;
    $('#basket_total_cost').html(newPrice);
}
function updateBasketAmount(){
   var tmp =  $('#basket_amount').html();
    if(!isNaN(tmp)){
   var oldAmount = parseInt(tmp.substr(0,2));
    var i = oldAmount + 1;;
    $('#basket_amount').html(
        ""+i+" vare(r)"
    );
    }else{
        $('#basket_amount').html(
            "1"+" vare(r)"
        );
    }
}
function goToBasket(){
    window.location.href = myBaseUrl+'Products/basket';
}

Javascript Solutions


Solution 1 - Javascript

I was having this problem when I started using select2 with XCrud. I solved it by disabling XCrud from loading JQuery, it was it a second time, and loading it below the body tag. So make sure JQuery isn't getting loaded twice on your page.

Solution 2 - Javascript

This error raises if your js files where you have bounded the select2 with select box is loading before select2 js files. Please make sure files should be in this order like..

  • Jquery
  • select2 js
  • your js

Solution 3 - Javascript

Had the same issue. Sorted it by defer loading select2

<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js" defer></script>

Solution 4 - Javascript

I was also facing same issue & notice that this error occurred because the selector on which I am using select2 did not exist or was not loaded.

So make sure that $("#selector") exists by doing

if ($("#selector").length > 0)
   $("#selector").select2();

Solution 5 - Javascript

Add $("#id").select2() out of document.ready() function.

Solution 6 - Javascript

I used the jQuery slim version and got this error. By using the normal jQuery version the issue got resolved.

Solution 7 - Javascript

The issue is quite old, but I'll put some small note as I spent couple of hours today investigating pretty same issue. After I loaded a part of code dynamically select2 couldn't work out on a new selectboxes with an error "$(...).select2 is not a function".

I found that in non-packed select2.js there is a line preventing it to reprocess the main function (in my 3.5.4 version it is in line 45):

> if (window.Select2 !== undefined) { > return; > }

So I just commented it out there and started to use select2.js (instead of minified version).

> //if (window.Select2 !== undefined) { > // return; > //}

And it started to work just fine, of course it now can do the processing several times loosing the performance, but I need it anyhow.

Hope this helps, Vladimir

Solution 8 - Javascript

you might be referring two jquery scripts which is giving the above error.

Solution 9 - Javascript

Put config.assets.debug = false in config/environments/development.rb.

Solution 10 - Javascript

For me, select2.min.js file worked instead of select2.full.min.js. I have manually define files which I have copied from dist folder that I got from github page. Also make sure that you have one jQuery(document).ready(...) definition and jquery file imported before select2 file.

Solution 11 - Javascript

For newbies like me, who end up on this question: This error also happens if you attempt to call .select2() on an element retrieved using pure javascript and not using jQuery.

This fails with the "select2 is not a function" error:

document.getElementById('e9').select2();

This works:

$("#e9").select2();

Solution 12 - Javascript

In my case, I was getting this error in my rails app when both webpacker and sprockets were trying to import jQuery. I didn't notice it until my code editor automatically tried to import jQuery into a webpacker module.

Solution 13 - Javascript

I was having the same problem today and none of the other answers worked. I don't understand how or why this worked, but it did and (knock on wood) still does.

But first, a bit about my specific situation:

I was using select2 in one .js file and trying to get it into another one, but got this error. jQuery was working fine in the other .js document, and the second one I tried to use was called LATER in the html than the first .js document I was writing, and both later than the jquery and select2

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMarc RasmussenView Question on Stackoverflow
Solution 1 - JavascriptFinbar DooleyView Answer on Stackoverflow
Solution 2 - JavascriptAshutosh SinghView Answer on Stackoverflow
Solution 3 - JavascriptAivis ZvezdovsView Answer on Stackoverflow
Solution 4 - JavascriptIrfan AshrafView Answer on Stackoverflow
Solution 5 - JavascriptArslan IshfaqView Answer on Stackoverflow
Solution 6 - JavascriptOrhanView Answer on Stackoverflow
Solution 7 - JavascriptVladimir TView Answer on Stackoverflow
Solution 8 - JavascriptAniket MainkarView Answer on Stackoverflow
Solution 9 - JavascriptRio DermawanView Answer on Stackoverflow
Solution 10 - JavascriptDeniz KaplanView Answer on Stackoverflow
Solution 11 - JavascriptjgermanView Answer on Stackoverflow
Solution 12 - JavascriptAustinView Answer on Stackoverflow
Solution 13 - JavascriptkingtorView Answer on Stackoverflow