Select2() is not a function - javascript

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';
}

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.

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

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>

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();

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

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

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

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

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

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.

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();

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.

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 tags.
OK, now for the solution that doesn't make sense, but does work:
I put the definition of the jQuery element into the earlier .js file and the .select2 on that variable in the later .js file. Weird, right? So, like this:
<head>
*blah blah blah html headers*
<script src="/static/js/jquery-3.6.0.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
</head>
<body>
*blah blah blah page stuff*
<script src="/static/js/first.js"></script>
*blah blah some more stuff*
<script src="/static/js/second.js"></script>
first.js
const selector = $('#select-this')
second.js
selector.select2({
*&c, &c, &c.*

ControlId.select2({...}); was not working but following worked:
$(ControlId).select2({...});

Related

Outputting data from an AJAX call to HTML

I'm using AJAX to add more articles to a list of articles when you press a button. So my AJAX call returns data that includes a title, author and 1 to 3 images associated with the article. Below is the code I'm using to output it, but it feels VERY clunky.
What are the best practices for printing out HTML with JavaScript/jQuery in a scenario like this where I need to add many new tags with new information? Thanks for the help!
Also, I know some of the code isn't super well written because it's a first draft just to make stuff work, so please only answer this question with regards to printing out the HTML or things that will make printing the HTML easier
$j.getJSON(ajaxurl, {action: 'load_articles', issues: $issues}, function(data) {
if (data.message != null) {
alert(data.message);
return
}
list = $j('.all-articles ul');
for (i in data.articles) {
article = data.articles[i];
//Hides articles already on page
if ($j("#" + article.id).size() === 0) {
list.append('<li class="article-preview" id="' + article.id + '">' +
'<h3 class="article-headline">' + article.title + '</h3>' +
'</li>');
current = $j("#" + article.id)
current.append('<p class="authors"></p>');
authors = $j("#" + article.id + " .authors")
for (a in article.authors) {
authors.append(article.authors[a].data.display_name + " ");
}
current.append('<div class="images"></div>');
images = $j("#" + article.id + " .images")
for (i in article.image) {
text = "<div class='image-expand-container'>";
if (i == 0) {
text += ('<img id="' + article.image[i].id + '"class="selected" src="' + article.image[i].medium + '"></img>');
}
else {
text += ('<img id="' + article.image[i].id + '" src="' + article.image[i].medium + '"></img>');
}
text += '<div class="dashicons dashicons-editor-expand"></div></div>';
images.append(text);
}
}
}
There are a few approaches you can take.
As you're doing here, you can return data from your ajax call (e.g. as JSON) and then use a javascript function to generate the corresponding HTML by building strings. This, as you're finding, is often messy.
You can generate the actual HTML on the server side, and have the ajax call return an HTML fragment, which you insert into your DOM. This has the advantage that, if some of your HTML is loading when the page loads, and some is loading via ajax, you can use the same approach (PHP, XSLT, ASP.NET Razor, any kind of server-side templating) to generate all of the HTML.
You can use a javascript templating framework to turn your JSON data into HTML. If all of your HTML is being generated via javascript (e.g. in a single-page application) this may be your best bet.

Selecting an image isn't working

I got some troubles working on javascript for an Firefox OS app, so I hope anyone can help me.
The case is I append some images from javascript (see code)
var aux = "<img class=\"imageOn\" id=\"" + imageName + "\"" + "src:\"" + imageURL + "\" >";
var image = "<a class=\"imageOn\" href=\"#\"> " + aux + " </a>";
$("#categoriasList").append(image);
$('#'+imageName).attr('src',imageURL);
And now I want to select one of these images from another js file:
$("img.imageOn").bind('click', function(e) {
console.log($(this).attr('id'));
playText($(this).attr('id'),"es");
// Change to picturesView
// Load icons from category choosed
});
The point is that actually it isn't working, the event is not triggered, so apendding or selecting the images has to be wrong, but I don't find the error. Does anyone know how to fix it?
Thank you in advanced.
Your src attribute should be followed by a = not a :
"<img class=\"imageOn\" id=\"" + imageName + "\"" + "src=\"" + imageURL + "\" >";
This
"src:\"
Should probably be
"src=\"
You need a = instead of : in your src. Try this:
"<img class=\"imageOn\" id=\"" + imageName + "\"" + "src=\"" + imageURL + "\" >";
If your are using jQuery you can use following method.
var aux= $(document.createElement('img')).attr(
'id':imageName,
'src':imageURL,
'class':'imageOn'
),
image = $(document.createElement('a')).attr({
'class':'imageOn'
'href':'#',
});
image.html(aux);
$("#categoriasList").append(image);
And after appending you can attach event handler. If you attaching without creating actual element it will not be triggered. It means if you want to attach event handler in the different file you should be sure that all elements already created. Otherwise there will not be triggered.
I fixed it using the event handler "on" of query

Passing variables to ajax with onclick

I have a problem with the variables, that I want to pass through ajax to php.
In an php file, I generate some divs with id and name attributes.
livesrc.php
echo "<div class=\"search-results\" id=\"" . $softwareArray['Sw_idn'] . "\"
name=\"" . $softwareArray['SoftwareName'] . "\"
onclick=\"addBasket(this.id, this.name)\" >
" . utf8_encode($softwareArray['SoftwareName']) . "</div>";
The relevent part is this:
onclick="addBasket(this.id, this.name)
Sorry for the escapes, in html the div looks like:
<div class="search-results" id="235"
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this.id, this.name)">...</div>
This looks okay, but in the js "addBasket", the variable sw_name is not set. (undefinded)
The JS in the head section:
<script type="text/javascript">
function addBasket(sw_id, sw_name)
{
alert(sw_name);
$.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data)
{
$("#basket").html(data);
});
}
</script>
The sw_id is set, but the sw_name is not working. Is the call in html with "this.name" correct?
it's because this.name did not exists if you want to access the attribute you have to call this.getAttribute('name') id are particular and can be access directly.
Personally I will give juste this to the function and extract id and name in the function
onclick="addBasket(this)";
<script type="text/javascript">
function addBasket(el)
{
var
sw_id = el.id,
sw_name = $(el).attr('name');
alert(sw_name);
$.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data)
{
$("#basket").html(data);
});
}
</script>
You could pass the whole element into your js:
<div class="search-results" id="235"
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this)">...</div>
Then grab what you want in your function
function addBasket(sw) {
alert( sw.id + ' ' + sw.getAttribute( 'name' ) );
}

Cannot get json results from twitter using PhoneGap and jQuery

I'm trying to get the last 50 tweets using a certain hash tag, on a mobile device using PhoneGap (0.9.6) and jQuery (1.6.1). Here's my code:
function getTweets(hash, numOfResults) {
var uri = "http://search.twitter.com/search.json?q=" + escape(hash) + "&callback=?&rpp=" + numOfResults;
console.log("uri: " + uri);
$.getJSON(uri, function(data) {
var items = [];
if(data.results.length > 0) {
console.log("got " + data.results.length + " results");
$.each(data.results, function(key, val) {
var item = "<li>";
item += "<img width='48px' height='48px' src='" + val.profile_image_url + "' />";
item += "<div class='tweet'><span class='author'>" + val.from_user + "</span>";
item += "<span class='tweettext'>" + val.text + "</span>";
item += "</div>";
item += "</li>";
items.push(item);
});
}
else {
console.log("no results found for " + hash);
items.push("<li>No Tweets about " + hash + " yet</li>");
}
$("#tweetresults").html($('<ul />', {html: items.join('')}));
});
}
This code works great in a browser, and for a while worked in the iPhone simulator. Now it's not working on either the iPhone or Android simulator. I do not see any of the console logs and it still works in a browser.
What am I doing wrong? If it's not possible to call getJson() on a mobile device using PhoneGap, what is my alternative (hopefully without resorting to native code - that would beat the purpose).
Bonus: how can I debug this on a mobile simulator? In a browser I use the dev tools or Firebug, but in the simulators, as mentioned, I don't even get the log messages.
As always, thanks for your time,
Guy
Update:
As #Greg intuited, the function wasn't called at all. Here's what I found and how I bypassed it:
I have this <a> element in the HTML Get tweets
Then I have this code in the $(document).ready() function:
$("#getTweets").click(function() {
var hash = "#bla";
getTweets(hash, 50);
});
That didn't call the function. But once I changed the code to:
function gt() {
var hash = "#bla";
getTweets(hash, 50);
}
and my HTML to:
Get Tweets
it now works and calls Twitter as intended. I have no idea what's screwed up with that particular click() binding, but I ran into similar issues with PhoneGap before. Any ideas are appreciated.
Considering that (a) there isn't much that could go wrong with the first line of your function and (b) the second line is a log command, then it would seem that the function isn't being called at all. You'll have to investigate the other code in your app.
Or are you saying that you don't have a way to read logged messages on your mobile devices?

Variable url in json-script

Messing around for days know. Learning javascript and jquery a few weeks, it goes well, but sometimes...
For an mobile app i'm trying to get the coordinates. Showing them on page isn't a problem, but I want them elsewhere.
In the main.js
var getLocation = function() {
var suc = function(p) {
document.getElementById("locatie").innerHTML = "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
};
var locFail = function() {
};
navigator.geolocation.getCurrentPosition(suc, locFail);
};
And in the htmlfile
<body onload="getLocation();" >
<p id="locatie">Finding geolocation...</p></ul>
<div id="geolocation">
Bezig met laden. Momentje geduld</div>
<script type="text/javascript">
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
function processTheseTerraces(jsonData){
var shtml = '';
var results = jsonData.results;
if(results){
$.each(results, function(index,value){
shtml += "<li class='store'><a class='noeffect' href='#'><span class='image' style='background-image: url(pics/terras1.jpg)'></span><span class='comment'>" + value.address + "</span><span class='name'>" + value.building_name + "</span><span class='stars5'></span><span class='starcomment'>132 Beoordelingen</span><span class='arrow'></span></a></li>";
});
$("#geolocation").html( shtml );
}
}
</script>
Now I want the coordinates passing through json and load the data. I thought to change
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
in
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20";
But that doesn't work. Anyone suggestions how I can solve this.
This: http://www.192.168.1.111 is just a wrong URL. I guess you need just this: http://192.168.1.111
Geolocation can take a long time (multiple seconds). It is an asynchronous request which means that the other javascript code may execute before the geolocation has grabbed the address. The solution is to put any code or function calls that use the location inside the callback function on the navigator.geolocation.getCurrentPosition
The JQuery is building the URL before the lat and lng have been defined.
onload="getLocation();" tells that when the document is loaded call getLocation function and inside this function you set the innerHTML of <P id="locatie"> TAG as: http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20
So problems are:
If you make a script tag and assign source then browser fetch the source data but writing an url on inner html of a <p> tag won't do this and it doesn't make sense.
Code fragment below is loaded before the document is loaded but i guess you do not want this:
jQuery(function(){
var script=document.createElement('script');
script.type='text/javascript';
script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=53.216493625&lon=6.557756660461426&max=20";
$("body").append(script);
});
If you want: script.src= "http://www.192.168.1.111/tools/gpslocation.php?lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20"; then you have to define p.coords first and before calling this otherwise p.coords is undefined.
Solution i am not sure what you exactly asking so could not answer. Do you want to assign inner HTML of the #locatie element or do you want to load customized script as tag?
Either ways, you have to make an ajax call to server which maybe like this:
$.ajax({
url: "http://www.192.168.1.111/tools/gpslocation.php",
data: "lat=" + p.coords.latitude + "&lon= " + p.coords.longitude + "&max=20",
success: function(Result){
// use Result variable in came from the success function.
document.getElementById("Your_ID_Goes_Here").innerHTML = "do_Something";
}
});

Categories

Resources