I have a function that is part of a fileupload, however when i try to validate the files through an array, wether i use an "accepted" file or a "wrong" file, i get the same end result which is the alert message on the return false statement of the code.
can someone spot an error here ? there are no syntax errors in the function.
handleFiles = function (files,e){
var rand = Math.floor((Math.random()*100000)+3);
for(var i=0, file; file = files[i]; i++) {
var fileType = new Array("psd","ai","eps","svg","png","doc","docx","jpg","jpeg","pptx","ppt","gif");
var file_extension = file.name.split('.').pop().toLowerCase();
if (parseInt(file.size / 1024) > 204800) {
alert("Filen er \""+file.name+"\" for stor");
return false;
}
if (fileType[i]==file_extension)
{
var src = '/printuploads/upload.png'
var template = '<div class="eachImage" id="'+rand+'">';
template += '<span class="preview" id="'+rand+'"><img src="'+src+'"><span class="overlay"><span class="updone"></span></span>';
template += '</span>'
template += '<div class="progress" id="'+rand+'"><span></span></div>';
if($("#dropbox .eachImage").html() == null)
$("#dropbox").html(template);
else
$("#dropbox").append(template);
upload(file,rand);
return true;
}
alert("Forkert filformat");
return false;
}
};
Your validation to check if the file extension is supported is incorrect:
fileType[i]==file_extension
Here, i is the index of file, not the extension. So every file extension is being compared with "psd".
Instead it should be checking if the extension is available in the array file_extension. You can do that using Array#some method:
fileType.some(t => t == file_extension)
Or, you can simply check that the extension belongs to the array using indexOf:
fileType.indexOf(file_extension) >= 0
Here's a working snippet, you can check the logged value in the console:
var handleFiles = function(files, e) {
var rand = Math.floor((Math.random() * 100000) + 3);
for (var i = 0, file; file = files[i]; i++) {
var fileType = new Array("psd", "ai", "eps", "svg", "png", "doc", "docx", "jpg", "jpeg", "pptx", "ppt", "gif");
var file_extension = file.name.split('.').pop().toLowerCase();
if (parseInt(file.size / 1024) > 204800) {
alert("Filen er \"" + file.name + "\" for stor");
return false;
}
if (fileType.some(t => t == file_extension)) {
console.log("Extension matches");
var src = '/printuploads/upload.png'
var template = '<div class="eachImage" id="' + rand + '">';
template += '<span class="preview" id="' + rand + '"><img src="' + src + '"><span class="overlay"><span class="updone"></span></span>';
template += '</span>'
template += '<div class="progress" id="' + rand + '"><span></span></div>';
if ($("#dropbox .eachImage").html() == null)
$("#dropbox").html(template);
else
$("#dropbox").append(template);
upload(file, rand);
return true;
}
alert("Forkert filformat");
return false;
}
};
function upload() {};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type ="file" onchange="handleFiles(this.files, event);">
Related
Any help is greatly appreciated! I've spent so long searching but I haven't found a solution or a problem like mine...
I'm writing an Electron application, and as part of it, there is a section for the users to drag and drop files. I'm then taking that file and uploading it to AWS S3.
The first time I drag and drop it goes into my function but no request is sent out to AWS S3, I then drag and drop again and it sends out the expected request and saves the file however it's the first requests information (name, path & body), and from then on when I drag and drop the file it send outs the request every time but always with the previous request's info. It's like its one sequence behind....
This is the s3 code:
function submitNewFileS3(file, filepath) {
const AWS = require('aws-sdk');
AWS.config = new AWS.Config({
accessKeyId: localStorage.getItem("accessKeyId"),
secretAccessKey: localStorage.getItem("secretAccessKey"),
region: 'eu-west-2'
});
var upload = new AWS.S3.ManagedUpload({
params: {
Bucket: 'sampe-bucket',
Key: filepath, // File name you want to save as in S3
Body: file
}
});
return upload.promise();
}
How I call the function:
var reader = new FileReader();
reader.onload = function (e2) {
// finished reading file data.
finishUploading(e2.target.result);
}
function finishUploading(url) {
// strip off the data: url prefix to get just the base64-encoded bytes
var data;
if (url.indexOf('data:image') > -1) {
data = url.replace(/^data:image\/\w+;base64,/, "");
} else if (url.indexOf('data:application') > -1) {
data = url.replace(/^data:application\/\w+;base64,/, "");
}
//only firing after sencon upload
var buf = Buffer.from(data, 'base64');
var filePathS3 = directory + (fileName).replace(/\-/g, "_").replace(/ /g, "_");
submitNewFileS3(buf, filePathS3).then(function (response) {
console.log(response);
}).catch(function (response) {
console.log(response);
});
}
reader.readAsDataURL(f); // start reading the file data.
Does anyone have any suggestions - I'm going out of my mind...I've tried so many tutorials and solutions and they all work...on the second call...
I've double checked all the required data is ready before making the request.
Many thanks in advance!
EDIT - more of what's going on in my main before sending my file to be uploaded:
function handleDrop(e) {
e.stopPropagation();
e.preventDefault();
var directory;
if (e.target.id == 'drop_zone_overview') {
//placed in general area, check which folders are showing to get dir
console.log(e);
//get whats visible
var whatPath;
$(".icon").each(function () {
if (this.style.display != 'none') {
whatPath = this.id;
}
});
//pick one and check what root we're in
var pathArray = whatPath.split('-');
console.log(pathArray);
} else if (e.target.id == 'drop_zone_individual') {
//placed on top of folder, check dir
directory = (e.target).getAttribute('data-targetfolder');
console.log(directory);
}
var files = e.dataTransfer.files,
folder;
for (var i = 0, f; f = files[i]; i++) { // iterate in the files dropped
if (!f.type && f.size % 4096 == 0) {
// The file is a folder
folder = true;
} else {
// The file is not a folder
folder = false;
}
const fs = require('fs');
console.log(f);
var fileName = f.name;
var reader = new FileReader();
reader.onload = function (e2) {
// finished reading file data.
finishUploading(e2.target.result);
}
function finishUploading(url) {
// strip off the data: url prefix to get just the base64-encoded bytes
var data;
if (url.indexOf('data:image') > -1) {
data = url.replace(/^data:image\/\w+;base64,/, "");
} else if (url.indexOf('data:application') > -1) {
data = url.replace(/^data:application\/\w+;base64,/, "");
}
var buf = Buffer.from(data, 'base64');
var filePathS3 = directory + (fileName).replace(/\-/g, "_").replace(/ /g, "_");
submitNewFileS3(buf, filePathS3).then(function (response) {
console.log(response);
}).catch(function (response) {
console.log(response);
});
}
reader.readAsDataURL(f); // start reading the file data.
uploadedFiles.push(f);
}
uploadedFiles.forEach(function (file) {
var pathKey = directory + (file.name).replace(/\-/g, "_");
pathKey = pathKey.replace(/ /g, "_").replace(/\//g, '-').replace(/\./g, '__');
if ($('#' + pathKey).length) {
//filename already exists in directory
alert(file.name + ' already exists in folder ' + directory);
} else {
var displayDiv;
if (file.type == 'image/png') {
//image
//add to directory
displayDiv = '<img id="' + pathKey + '" class="fileInfo thumb file-type file-type-img" src="' + URL.createObjectURL(file) + '" ondblclick="preview_image(this)"/>'
} else if (file.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
//xlsx doc
displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-xlsx" data-downloadLink="' + URL.createObjectURL(file) + '" ></div>';
} else if (file.type == 'application/pdf') {
//pdf doc
displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-pdf" data-downloadLink="' + URL.createObjectURL(file) + '" ></div>';
} else if (file.type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
//word doc
displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-docx" data-downloadLink="' + URL.createObjectURL(file) + '" </div>';
console.log('its a doc');
} else if (file.type == 'application/x-zip-compressed') {
//zip file doc
displayDiv = '<div id="' + pathKey + '" class="fileInfo thumb file-type file-type-zip" data-downloadLink="' + URL.createObjectURL(file) + '" </div>';
} else if (file.type == '') {
//folder
console.log('what typep is this~~~~~ ' + file.type);
file.name = file.name + '/';
}
//save to folder array
if (file.type == 'application/x-zip-compressed' || file.type == '') {
var htmlTemplate = [
getHtml([
'<li id=' + pathKey.replace(/ /g, "_").replace(/\//g, '-').replace(/\./g, '__') + ' class="icon folderItems fileInfo thumb" data-downloadLink="directory_' + pathKey + '" ondblclick="viewAlbum(this.id)" style="display:none">',
'<i id="drop_zone_individual" data-targetFolder="' + pathKey + '" class="folders fas fa-folder" style="font-size: 115px; color: rgb(13, 36, 60); cursor: pointer;"></i>',
'<div class="folderLabel" style="text-align:center">' + file.name + '</div>',
'</li>'
])
];
folders.push({
Key: directory + (file.name).replace(/\-/g, "_").replace(/ /g, "_"),
LastModified: file.lastModifiedDate,
Size: file.size,
});
} else {
//append to ui file list
var htmlTemplate = [
getHtml([
'<li id=' + pathKey + ' class="icon downloadableItem" style="display:none">',
'<span>',
'<div style="text-align:center">',
displayDiv,
'</div>',
'<div style="text-align:center">',
'<span>',
file.name,
'</span>',
'</div>',
'</span>',
'</li>'
])
];
//save to folder list
folders.push({
Key: directory + (file.name).replace(/\-/g, "_").replace(/ /g, "_"),
LastModified: file.lastModifiedDate,
Size: file.size,
signedUrl: URL.createObjectURL(file)
});
}
localStorage.setItem("s3Objects", JSON.stringify(folders));
$('#photoAlbumViewerList').append(htmlTemplate);
console.log(folders);
$("#" + pathKey).click(function (e) {
getAlbumInfo(this.id);
if (e.shiftKey) {
if ($(this).hasClass('thumb')) {
$(this).removeClass('thumb').addClass('thumbChecked');
$(this).css("border", "2px solid #c32032");
// $(this).attr("data-downloadLink");
links.push($(this).attr("data-downloadLink"));
if (links.length != 0) {
$('.download').css("display", "block");
}
} else if ($(this).hasClass('thumbChecked')) {
$(this).removeClass('thumbChecked').addClass('thumb');
$(this).css("border", "2px solid white");
var itemtoRemove = $(this).attr('src');
links.splice($.inArray(itemtoRemove, links), 1);
console.log(links);
if (links.length == 0) {
$('.download').css("display", "none");
}
}
}
});
}
});
uploadedFiles = [];
e.target.classList.remove('drop_zone_hovered');
$('#drop_zone_text').hide();
}
As an FYI - the issue lied where I reinitialised AWS and S3 variables, it wasn't needed as I set it at the start of launch and reinitialising it slowed it all down while it remade the connection!
I got this code here in a JS file, where I've put two console.log(), one at the beginning and one at the end, to see why I'm having problems targeting the with a specific ID / class. Now I see that the console.log() at the end loads before the one in the beginning. Even when I place a console.log() outside of the file underneath the <script> tag which loads this JS file, it loads before the JS file, which doesn't make any sense to me. How can I fix this problem?
/*!
* jquery.instagramFeed
*
* #version 1.2.7
*
* #author Javier Sanahuja Liebana <bannss1#gmail.com>
* #contributor csanahuja <csanahuja10#gmail.com>
*
* https://github.com/jsanahuja/jquery.instagramFeed
*
*/
(function($){
var defaults = {
'host': "https://www.instagram.com/",
'username': 'username',
'tag': '',
'container': '#instagram',
'display_profile': true,
'display_biography': true,
'display_gallery': true,
'display_igtv': false,
'get_data': false,
'callback': null,
'styling': true,
'items': 8,
'items_per_row': 4,
'margin': 0.5,
'image_size': 640
};
var image_sizes = {
"150": 0,
"240": 1,
"320": 2,
"480": 3,
"640": 4
};
var escape_map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '='
};
function escape_string(str){
return str.replace(/[&<>"'`=\/]/g, function (char) {
return escape_map[char];
});
}
$.instagramFeed = function(opts){
//console log at the beginning of the function
console.log("Beginning instagramFeed");
var options = $.fn.extend({}, defaults, opts);
if(options.username == "" && options.tag == ""){
console.error("Instagram Feed: Error, no username or tag found.");
return false;
}
if(typeof options.get_raw_json !== "undefined"){
console.warn("Instagram Feed: get_raw_json is deprecated. See use get_data instead");
options.get_data = options.get_raw_json;
}
if(!options.get_data && options.container == ""){
console.error("Instagram Feed: Error, no container found.");
return false;
}
if(options.get_data && options.callback == null){
console.error("Instagram Feed: Error, no callback defined to get the raw json");
return false;
}
var is_tag = options.username == "",
url = is_tag ? options.host + "explore/tags/"+ options.tag + "/" : options.host + options.username + "/";
$.get(url, function(data){
try{
data = data.split("window._sharedData = ")[1].split("<\/script>")[0];
}catch(e){
console.error("Instagram Feed: It looks like the profile you are trying to fetch is age restricted. See https://github.com/jsanahuja/InstagramFeed/issues/26");
return;
}
data = JSON.parse(data.substr(0, data.length - 1));
data = data.entry_data.ProfilePage || data.entry_data.TagPage;
if(typeof data === "undefined"){
console.error("Instagram Feed: It looks like YOUR network has been temporary banned because of too many requests. See https://github.com/jsanahuja/jquery.instagramFeed/issues/25");
return;
}
data = data[0].graphql.user || data[0].graphql.hashtag;
if(options.get_data){
options.callback(data);
return;
}
//Setting styles
var styles = {
'profile_container': "",
'profile_image': "",
'profile_name': "",
'profile_biography': "",
'gallery_image': ""
};
if(options.styling){
styles.profile_container = " style='text-align:center;'";
styles.profile_image = " style='border-radius:10em;width:15%;max-width:125px;min-width:50px;'";
styles.profile_name = " style='font-size:1.2em;'";
styles.profile_biography = " style='font-size:1em;'";
var width = (100 - options.margin * 2 * options.items_per_row)/options.items_per_row;
styles.gallery_image = " style='margin:"+options.margin+"% "+options.margin+"%;width:"+width+"%;float:left;'";
}
var html = "";
//Displaying profile
if(options.display_profile){
html += "<div class='instagram_profile'" +styles.profile_container +">";
html += "<img class='instagram_profile_image' src='"+ data.profile_pic_url +"' alt='"+ (is_tag ? data.name + " tag pic" : data.username + " profile pic") +"'"+ styles.profile_image +" />";
if(is_tag)
html += "<p class='instagram_tag'"+ styles.profile_name +"><a href='https://www.instagram.com/explore/tags/"+ options.tag +"' rel='noopener' target='_blank'>#"+ options.tag +"</a></p>";
else
html += "<p class='instagram_username'"+ styles.profile_name +">#"+ data.full_name +" (<a href='https://www.instagram.com/"+ options.username +"' rel='noopener' target='_blank'>#"+options.username+"</a>)</p>";
if(!is_tag && options.display_biography)
html += "<p class='instagram_biography'"+ styles.profile_biography +">"+ data.biography +"</p>";
html += "</div>";
}
//image size
var image_index = typeof image_sizes[options.image_size] !== "undefined" ? image_sizes[options.image_size] : image_sizes[640];
if(options.display_gallery){
if(typeof data.is_private !== "undefined" && data.is_private === true){
html += "<p class='instagram_private'><strong>This profile is private</strong></p>";
}else{
var imgs = (data.edge_owner_to_timeline_media || data.edge_hashtag_to_media).edges;
max = (imgs.length > options.items) ? options.items : imgs.length;
html += "<div class='instagram_gallery'>";
for(var i = 0; i < max; i++){
var url = "https://www.instagram.com/p/" + imgs[i].node.shortcode,
image, type_resource, caption, date, likes, comments;
switch(imgs[i].node.__typename){
case "GraphSidecar":
type_resource = "sidecar"
image = imgs[i].node.thumbnail_resources[image_index].src;
date = new Date(imgs[i].node.taken_at_timestamp * 1000);
likes = imgs[i].node.edge_media_preview_like.count;
comments = imgs[i].node.edge_media_to_comment.count;
break;
case "GraphVideo":
type_resource = "video";
image = imgs[i].node.thumbnail_src
break;
default:
type_resource = "image";
image = imgs[i].node.thumbnail_resources[image_index].src;
date = new Date(imgs[i].node.taken_at_timestamp * 1000);
likes = imgs[i].node.edge_media_preview_like.count;
comments = imgs[i].node.edge_media_to_comment.count;
}
console.log(date);
console.log(likes);
console.log(comments);
if(
typeof imgs[i].node.edge_media_to_caption.edges[0] !== "undefined" &&
typeof imgs[i].node.edge_media_to_caption.edges[0].node !== "undefined" &&
typeof imgs[i].node.edge_media_to_caption.edges[0].node.text !== "undefined" &&
imgs[i].node.edge_media_to_caption.edges[0].node.text !== null
){
caption = imgs[i].node.edge_media_to_caption.edges[0].node.text;
}else if(
typeof imgs[i].node.accessibility_caption !== "undefined" &&
imgs[i].node.accessibility_caption !== null
){
caption = imgs[i].node.accessibility_caption;
}else{
caption = (is_tag ? data.name : data.username) + " image " + i;
}
html += "<a id='instagramID" + i + "' class='instagramimg instagram-" + type_resource + "' rel='noopener' target='_blank'>";
html += "<img class='instagramicon' src='https://cdn.shopify.com/s/files/1/0278/9644/7113/files/instagram-icon.svg?v=1592246117' alt='instagramicon'>";
html += "<div class='instagramhover'></div>";
html += "<img src='" + image + "' alt='" + escape_string(caption) + "'"/* + styles.gallery_image*/ +" />";
html += "</a>";
}
}
}
if(options.display_igtv && typeof data.edge_felix_video_timeline !== "undefined"){
var igtv = data.edge_felix_video_timeline.edges,
max = (igtv.length > options.items) ? options.items : igtv.length
if(igtv.length > 0){
html += "<div class='instagram_igtv'>";
for(var i = 0; i < max; i++){
html += "<a href='https://www.instagram.com/p/"+ igtv[i].node.shortcode +"' rel='noopener' target='_blank'>";
html += "<img src='"+ igtv[i].node.thumbnail_src +"' alt='"+ options.username +" instagram image "+ i+"'"+styles.gallery_image+" />";
html += "</a>";
}
html += "</div>";
}
}
$(options.container).html(html);
}).fail(function(e){
console.error("Instagram Feed: Unable to fetch the given user/tag. Instagram responded with the status code: ", e.status);
});
return true;
};
// Ending of the code
console.log("Ending instagramFeed");
})(jQuery);
This function gets called like this in the html part. Also here, the console.log("before instagramFeed.JS"); loads together with console.log("after instagramFeed.JS");, and after that I receive the
console.log(date);
console.log(likes);
console.log(comments);
which are inside the for loop of the function.
<script src="{{ 'jquery.instagramFeed.js' | asset_url }}"></script>
<div id="instagram"></div>
<script>
console.log("before instagramFeed.JS");
(function($){
$(window).on('load', function(){
$.instagramFeed({
'username': 'username',
'container': "#instagram",
'display_profile': false,
'display_biography': false,
'display_gallery': true,
'callback': null,
'styling': true,
'items': 10,
'items_per_row': 5,
'margin': 0.2
});
});
})(jQuery);
console.log("after instagramFeed.JS");
</script>
Your code is executed in the following order:
first snippet (definition of instagramFeed plugin) is executed during page load. console.log statements outside of that plugin are executed as well.
window is loaded (all script tag contents are read and executed), your window load handler kicks in. It calls your instagramFeed function the way you set it in the second snippet. before/after instagramFeed.JS logs are executed here. instagramFeed function starts a network call the result of which is processed after the load handler finishes running.
network call response is processed. comments, likes and date are logged at this stage.
As a result, everything is working as expected if I understand the purpose correctly.
UPD: to use the elements generated by network call response handler (provided you have an opportunity to edit the plugin code directly) you can add a function into options object, say onImageElementsCreated and call it after the loop in the plugin. Then you can provide your function as another option in the second snippet.
I can't say this with 100% certainty, as I haven't run the code.
However, I think the line console.log("Ending instagramFeed"); is being run before the line console.log("Beginning instagramFeed");, because it's outside the function $.instagramFeed = function(opts).
The function is created, then the ending log line is called, then something is calling the function, then the beginning log line is called.
Where in your code do you call $.instagramFeed()?
I got webpage with JS code that get randomize Object from array and show it's value with Jquery .html() code in some div.
That work great.
When I click on a another page on the website it also look great, but when I click back on the browser, the code what created max the JavaScript Variables and I get the wrong text in the wrong placement
Any Tip what should I look for?
function showMoodaa(size, divID, countshow) {
if (typeof(countshow) === 'undefined')
countshow = 1;
var rndBanner = "";
var htmlcode = "";
if (modaoot[size] != undefined) {
if (countshow > 1) {
var countMoodaa = modaoot[size].length;
if (countMoodaa > countshow) {
countMoodaa = countshow;
}
rndBanner = Math.floor(Math.random() * modaoot[size].length);
for (i = 0; i < countMoodaa; i++) {
if ((rndBanner + i) >= modaoot[size].length) {
htmlcode = htmlcode + (modaoot[size][rndBanner + i - countMoodaa].html);
window.numBanner = window.numBanner + modaoot[size][rndBanner + i - countMoodaa].id + ",";
} else {
htmlcode = htmlcode + (modaoot[size][rndBanner + i].html);
window.numBanner = window.numBanner + modaoot[size][rndBanner + i].id + ",";
}
}
} else {
rndBanner = Math.floor(Math.random() * modaoot[size].length);
window.numBanner = window.numBanner + modaoot[size][rndBanner].id + ",";
htmlcode = modaoot[size][rndBanner].html;
}
} else {
htmlcode = "<!-- no size like this in array-->";
}
$("#" + divID).append(htmlcode);
}
showMoodaa(2, "pos1");
showMoodaa(2, "pos2");
showMoodaa(10, "pos1", 2);
I implemented a following HTML <input> multiple Attribute
<input type="file" name="R" id="someattachId" multiple="multiple" style='display:none' />
I'm trying to remove specific item in it using following code
$('#someattachId')[0].files[fileId].remove();
but it can't remove it.
No, We can make it removable.
I implemented this and it works definitely.
First you need to initialize this variables
var newImageObj = [];
var ImageNo = 0;
Then write this code on file input's change
$("#exampleInputFileProduct").change(function () {
var fileUpload = document.getElementById("exampleInputFileProduct");
//$("#mainImages").html('');
//$("#subImages").html('');
if (typeof (FileReader) != "undefined") {
//Here Check File Extension
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png)$/;
for (var i = 0; i < fileUpload.files.length; i++) {
var j = 0;
var file = fileUpload.files[i];
var NewFile = fileUpload.files[i];
//Here Check File Size 1MB = 1000000 Bytes
if (file.size < 2048000) {
if (regex.test(file.name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
if ($("#mainImages").find(".item").attr("id") == "FirstSlider") {
$("#mainImages").html('');
$("#subImages").html('');
$("#subImages").append("<div class='item active'></div>");
}
if ($("#mainImages").find(".item").hasClass("active")) {
$("#mainImages").append("<div class='item " + ImageNo + "_CClass\'><i class='fa fa-times customIcon' onclick='RemoveImage(\"" + ImageNo + "_CClass\",\"" + fileUpload.files[j].name.toLowerCase() + "\")'></i><img class='CImage' src='" + e.target.result + "' alt='' /></div>");
} else {
$("#mainImages").append("<div class='item active " + ImageNo + "_CClass'><i class='fa fa-times customIcon' onclick='RemoveImage(\"" + ImageNo + "_CClass\",\"" + fileUpload.files[j].name.toLowerCase() + "\")'></i><img class='CImage' src='" + e.target.result + "' alt='' /></div>");
}
//if ($("#subImages").find(".item").length == 0) {
// $("#subImages").append("<div class='item active'></div>");
//} else {
if (($("#subImages").find(".item").find("div").length / 5) >= $("#subImages").find(".item").length) {
$("#subImages").append("<div class='item'></div>");
}
//}
var append = 0;
$.each($("#subImages").find(".item"), function (p, pelement) {
if (append == 0) {
if ($(pelement).find("div").length != 5) {
var newID = $(pelement).find("div").length;
newID = newID;
$(pelement).append("<div onclick='LoadImage(\"" + ImageNo + "_CClass\")' data-slide-to='" + newID + "' class='thumb " + ImageNo + "_CClass'> <img src='" + e.target.result + "' alt=''></div>");
append = append + 1;
}
}
})
j = j + 1;
ImageNo = ImageNo + 1;
}
newImageObj.push(file);
reader.readAsDataURL(file);
}
}
}
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
Then at last this 2 functions will help to do the rest
function LoadImage(objclass) {
$("#mainImages").find(".item").removeClass("active");
$("#mainImages").find("." + objclass + "").addClass("active");
}
function RemoveImage(objclass, ImageName) {
$.each(newImageObj, function (e, element) {
if ($(this)[0].name.toLowerCase().trim() == ImageName.trim()) {
newImageObj.pop(this);
}
});
$("#mainImages").find("." + objclass + "").remove();
$("#subImages").find(".item").find("." + objclass + "").remove();
if ($("#mainImages").find(".item").length == 0) {
$("#mainImages").append("<div class='item active'><i class='fa fa-times customIcon'></i><img class='CImage' src='/Content/img/DefaultProduct.gif' alt='' /></div>");
$("#subImages").append("<div class='item active'><div data-target='#carousel' data-slide-to='0' class='thumb'> <img src='/Content/img/DefaultProduct.gif' alt=''></div></div></div>");
} else {
$("#mainImages").find(".item").removeClass("active");
$("#mainImages").find(".item:first-child").addClass("active");
$("#subImages").find(".item").removeClass("active");
$("#subImages").find(".item:first-child").addClass("active");
}
}
At last when you submit your form than take the files from the array
I'm trying to build a simple site that will check and print out "Buy It Now Prices" for cars. I can't get the JavaScript push function to print out anything but strings.
The eBay API says that buyItNowPrice returns an Amount.
I have experimented with the other Item functions, and the only ones that are working for me are ones that return a String.
The question is, how should the line var itemPrice = item.buyItNowPrice; be formatted to output a number?
function _cb_findItemsByKeywords(root) {
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
var itemPrice = item.buyItNowPrice;
var timeLeft = item.watchCount;
if (title != null && null != viewitem) {
html.push('<tr><td>' + '<img src="' + pic + '" border="1">' + '</td>' +
'<td><a href="' + viewitem + '" target="_blank">' +
title + '</a>' // end hyperlink
+
'<br>Item Price: ' + itemPrice +
'<br>Time Remaining: ' + timeLeft +
'</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [{
"name": "MaxPrice",
"value": "250000",
"paramName": "Currency",
"paramValue": "USD"
},
{
"name": "MinPrice",
"value": "15000",
"paramName": "Currency",
"paramValue": "USD"
},
//{"name":"FreeShippingOnly", "value":"false", "paramName":"", "paramValue":""},
{
"name": "ListingType",
"value": ["AuctionWithBIN", "FixedPrice", /*"StoreInventory"*/ ],
"paramName": "",
"paramValue": ""
},
];
// Generates an indexed URL snippet from the array of item filters
var urlfilter = "";
function buildURLArray() {
for (var i = 0; i < filterarray.length; i++) {
var itemfilter = filterarray[i];
for (var index in itemfilter) {
// Check to see if the paramter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for (var r = 0; r < itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value;
}
} else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
}
buildURLArray(filterarray);
// Construct the request
var url = "http://svcs.ebay.com/services/search/FindingService/v1";
url += "?OPERATION-NAME=findItemsByKeywords";
url += "&SERVICE-VERSION=1.0.0";
url += "&SECURITY-APPNAME=REDACTED";
url += "&GLOBAL-ID=EBAY-MOTOR";
url += "&RESPONSE-DATA-FORMAT=JSON";
url += "&callback=_cb_findItemsByKeywords";
url += "&REST-PAYLOAD";
//url += "&categoryId=6001";
url += "&keywords=Ferrari 575";
url += "&paginationInput.entriesPerPage=12";
url += urlfilter;
// Submit the request
s = document.createElement('script'); // create script element
s.src = url;
document.body.appendChild(s);
You are reading the wrong eBay documentation. FindItemsByKeywords is part of the Finding API service. The buyItNowPrice field is found in the item.listingInfo field. Changing the code to the following will output the price.
var itemPrice = '---';
// buyItNowPrice may not be returned for all results.
if(item.listingInfo[0].buyItNowPrice) {
itemPrice = item.listingInfo[0].buyItNowPrice[0]['#currencyId'] + ' ' + item.listingInfo[0].buyItNowPrice[0].__value__;
} else if(item.sellingStatus[0].currentPrice) {
itemPrice = item.sellingStatus[0].currentPrice[0]['#currencyId'] + ' ' + item.sellingStatus[0].currentPrice[0].__value__;
}