I use WinJS in my application and try to print some content. Made my printer class according to this tutorial https://dzone.com/articles/windows-8-print-contract-%E2%80%93.
function registerForPrintContract(participiantData) {
var printManager = Windows.Graphics.Printing.PrintManager.getForCurrentView();
printManager.addEventListener("printtaskrequested", onPrintTaskRequested, false);
}
function onPrintTaskRequested(printEvent) {
var printTask = printEvent.request.createPrintTask("Print Example", function (args) {
printCurrentPage(args);
printTask.oncompleted = onPrintTaskCompleted;
});
}
function printCurrentPage(args) {
var docHtml = document.createDocumentFragment();
docHtml.appendChild(createDocumentContent());
args.setSource(MSApp.getHtmlPrintDocumentSource(docHtml));
}
function createDocumentContent() {
var container = document.createElement("div");
container.innerHTML = "<h2>" + firstname + " " + lastname + "</h2>" +
"<h4>" + emailaddress1 + "<h4>";
return container;
}
function showPrintUI() {
Windows.Graphics.Printing.PrintManager.showPrintUIAsync();
}
My problem is that I do not know how to forward some object data to createDocumentContent() function. In this example I put firstname, lastname and email. Those data I cannot get from html page I need to send them on print button click.
All examples I saw are about printing current page or making new content from data which we can get from HTML page by querying DOM, no example where I can send custom object.
What is the best way to do this ?
My problem is that I do not know how to forward some object data to createDocumentContent() function. In this example I put firstname, lastname and email. Those data I cannot get from html page I need to send them on print button click.
Do you mean you want to put the html output of "<h2>"+firstname + " " +lastname+"</h2>"+"<h4>" + emailaddress1 + "<h4>" to your print page?
The behavior of innerHTML has changed in Windows Store App Development.
see HTML and DOM API changes list innerHTML section:
Content is filtered as through it was processed by the toStaticHTML method
But WinJS offers a method that you can utilize to inject HTML.
Here is the link to documentation of this method: WinJS.Utilities.insertAdjacentHTML
Here is a code snippet that shows a simple use this method:
function createDocumentContent() {
var obj = {
firstname: "winffee",
lastname: "xia",
emailaddress1:"test#126.com"
}
var htmlString = "<h2>" + obj.firstname + " " + obj.lastname + "</h2>" +
"<h4>" + obj.emailaddress1 + "<h4>";
var container = document.createElement("div");
WinJS.Utilities.insertAdjacentHTML(container, "beforeend", htmlString);
return container;
}
I want to create something like Facebook wall. Currently I am getting the data in a json format and displaying using jQuery $each and then appending it to the main div. I am looking for an alternative way of doing this.
The problem in the current code is that i cannot use the div class to call any method like on.click . The on.click method need to be inside the $each to be get called and it gets called the number of object present in data.
And if i want to update the wall then i need to update the data and has to refresh the whole structure. Is there any other way by which i can add the new post to the wall without rebuilding the structure.
$.each(data, function () {
var status_id = this['Id'];
var like_id = "like" + status_id;
var commennt_id = "commnet-tem" + status_id;
var likes = 0;
$("<div class=\"post-indi\" id=\"post-item" + status_id + "\">" +
"<div class=\"post-content\">" +
" <div class=\"status-profile\" >" +
"<img src="">" +
"</div>" +
"<div class=\"content\">" + this['status'] + "</div>" +
"</div>" +
"<div class=\"commentbox-info\">" +
"<a id=\""+like_id+"\" href=\"#\" class=\"postddlike\">Like</a><img </div></div>").appendTo("div.post");
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({...});
I've been developing a web game, with jquery doing some of the work. It was on a server, but I've moved it back to my laptop. Everything seems to work fine, except the most important function, which imports the contents of an html file.
$(".ReportList a").live('click', function(){
var getreportname = $(this).text();
$("#scroller").append("<span>The reportname is " + getreportname + "</span>");
var usersreport = "ReportList_" + User + "";
jQuery.get('Reports/' + getreportname + '.html', function (data) {
$("#" + usersreport).html(data);
$("#" + usersreport + " span").addClass("Py" + User);
updateCount();
});
});
Not sure why it stopped working. Would appreciate any insight.
I didn't need the .get() method to do what I wanted, .html() was good enough if I re-formulated the script.
Could anyone please advise me of what am I doing wrong here?
I am trying to construct the image URL but using the flickr.photos.search method
now (I need to display images close to geolocation of the visitor), I had it
working before with groups_pool.gne and the JSON feed was different (simpler)
formatted but now..
The URL is working, I get the array with all the data I need (farm, server,
secret and id) but can't construct the url for the photo.
$.getJSON("http://api.flickr.com/services/rest/?method=flickr.photos.search&api_\
key=KEY&format=json&privacy_filter=0&media=photos&has_geo=1&accuracy=13&sort=int\
erestingness-desc&content_type=1&per_page=32&extras=geo,owner_name&page=1&radius\
_units=km&radius=1.521739&lat=40.952532&lon=-4.1326349999999366&text=Alcazar&jso\
ncallback=jsonp1320163051486", getJSONimages);
function getJSONimages(data) {
var htmlString = "";
$.each(data.photos.photo, function(i,item){
htmlString += '<img src="http://farm'+ item.farm +'.static.flickr.com/'+
item.server +'/'+ item.id +'_'+ item.secret +'_m.jpg" />';
});
$('#slideshow').html(htmlString);
Thank you.
I have added the url_m in the extras, in the URL to get the JSON feed and I get the full URL in my feed and that should help as I do not have to concatenate the rest but still doesn't work.
I can't get it to work, and it's extremely frustrating as I know is very simple.
Well, not for me obviously.
This is my function, after I get the url_m in the loop:
function getJSONimages(data) {
var htmlString = "";
$.each(data.photos.photo, function(i,item){
// var url = (item.url_m).replace("\", "");
htmlString += '<img src="' + item.url_m + '" />';
});
$('#slideshow').html(htmlString);
}
Even if I use the "url" variable or no, same result.
However, I have noticed something.
In the feed using groups_pool.gne, where I am able to pull the photos
successfully, I go to the media.m like that:
$.each(data.items, function(i,item){
var biggestSize = (item.media.m).replace("_m.jpg", ".jpg");
htmlString += '<img src="' + biggestSize + '" />';
Notice that I have items, then media, then m with it's own value! Is actually
items.[media: {m:PHOTOURL}].
Where as in this other JSON feed using the flickr.photos.search method, I have
the following "object path":
jsonFlickrApi.photos.photo[{url_m:PHOTOURL}]
And try to use this loop:
$.each(data.photos.photo, function(i,item){
htmlString += '<img src="' + item.url_m + '" />';
I think this is my problem but I don't have any ideas how to approach it. It's
obvious there is a different structure between the two feeds:
items.[media: {m:PHOTOURL}]
photos.photo[{url_m:PHOTOURL}]
I am going to research more on jQuery loops. Any ideas?
Weirdly these docs don't mention getting the farm. Can you console.log your item in the $.each loop and see what you get?
http://www.flickr.com/services/api/flickr.photos.search.html
It's clearly the right URL format though assuming you get all of those pieces:
http://www.flickr.com/services/api/misc.urls.html
EDIT
Can you tell me what this says (in the alert box):
$.each(data.photos.photo, function(i,item){
var url = 'http://farm'+ item.farm +'.static.flickr.com/' + item.server +'/'+ item.id +'_'+ item.secret +'_m.jpg';
alert(url);
});
A URL is not a JSON object so you cannot parse it.
You're trying get the URL parameters.
Include the following function and use it like this.
lat = querySt('lat');
lon = querySt('lon');
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
You might want to modify this part
hu =window.location.search.substring(1);
to
hu = yourURLVariable;
if you're getting the URL from somewhere else.