Cancel one file to upload jQuery - javascript

With id="cancel_upload" I want to delete one file in the queue to upload with jQuery, is there a way to do this? this is my code:
$("#files").on("change", function() {
var fp = $("#files");
var lg = fp[0].files.length;
var items = fp[0].files;
var fragment = "";
if (lg > 4) {
alert('Upload maksimal 4 file!');
return false;
} else {
$("#list_file").show();
for (var i = 0; i < lg; i++) {
var fileName = items[i].name;
var fileSize = items[i].size;
fragment += '<div class="item">' + '<a class="ui label">' + "(" + formatFileSize(fileSize) + ") " + fileName + '<i class="delete icon" id="cancel_upload"></i>' + "</a>" + "</div>" + "<br>";
}
$("#list_file").append(fragment);
$("#files").prop('disabled', true);
}
});
$("cancel_upload").on('click', function() {
fileName.abort();
});

Try something like
var ajaxCalll;
$("#files").on("change", function() {
var fp = $("#files");
var lg = fp[0].files.length;
var items = fp[0].files;
var fragment = "";
if (lg > 4) {
alert('Upload maksimal 4 file!');
return false;
} else {
$("#list_file").show();
for (var i = 0; i < lg; i++) {
var fileName = items[i].name;
var fileSize = items[i].size;
fragment += '<div class="item">' + '<a class="ui label">' + "(" + formatFileSize(fileSize) + ") " + fileName + '<i class="delete icon" id="cancel_upload"></i>' + "</a>" + "</div>" + "<br>";
}
$("#list_file").append(fragment);
$("#files").prop('disabled', true);
// assign AJAX Call to ajaxCalll variable
}
});
$("#cancel_upload").on('click', function() {
ajaxCalll.abort();
});
Hope this will help you.

Related

Google Ads scripts - how to do customised or long rolling date ranges

I'm using the following script to export Google Ads data from my account, but I am stuck with Google's pre-set date ranges and can't figure out how/if it's possible to jimmy these. Ideal date range would be year to date, with the report refreshing each day and adding on a fresh day's data, but would also be interested if we can get all time to work.
I'm a coding novice, so apologies in advance.
Script:
function main() {
var currentSetting = new Object();
currentSetting.ss = SPREADSHEET_URL;
// Read Settings Sheet
var settingsSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(SETTINGS_SHEET_NAME);
var rows = settingsSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
var sortString = "";
var filters = new Array();
for(var i = 0; i < numRows; i++) {
var row = values[i];
var settingName = row[0];
var settingOperator = row[1];
var settingValue = row[2];
var dataType = row[3];
debug(settingName + " " + settingOperator + " " + settingValue);
if(settingName.toLowerCase().indexOf("report type") != -1) {
var reportType = settingValue;
} else if(settingName.toLowerCase().indexOf("date range") != -1) {
var dateRange = settingValue;
} else if(settingName.toLowerCase().indexOf("sort order") != -1) {
var sortDirection = dataType || "DESC";
if(settingValue) var sortString = "ORDER BY " + settingValue + " " + sortDirection;
var sortColumnIndex = 1;
}else {
if(settingOperator && settingValue) {
if(dataType.toLowerCase().indexOf("long") != -1 || dataType.toLowerCase().indexOf("double") != -1 || dataType.toLowerCase().indexOf("money") != -1 || dataType.toLowerCase().indexOf("integer") != -1) {
var filter = settingName + " " + settingOperator + " " + settingValue;
} else {
if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + ' "' + settingValue + '"';
} else if(settingValue.indexOf("'") != -1) {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
} else {
var filter = settingName + " " + settingOperator + " '" + settingValue + "'";
}
}
debug("filter: " + filter)
filters.push(filter);
}
}
}
// Process the report sheet and fill in the data
var reportSheet = SpreadsheetApp.openByUrl(currentSetting.ss).getSheetByName(REPORT_SHEET_NAME);
var rows = reportSheet.getDataRange();
var numRows = rows.getNumRows();
var numCols = rows.getNumColumns();
var values = rows.getValues();
var numSettingsRows = numRows - 1;
// Read Header Row and match names to settings
var headerNames = new Array();
var row = values[0];
for(var i = 0; i < numCols; i++) {
var value = row[i];
headerNames.push(value);
//debug(value);
}
if(reportType.toLowerCase().indexOf("performance") != -1) {
var dateString = ' DURING ' + dateRange;
} else {
var dateString = "";
}
if(filters.length) {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + ' WHERE ' + filters.join(" AND ") + dateString + " " + sortString;
} else {
var query = 'SELECT ' + headerNames.join(",") + ' FROM ' + reportType + dateString + " " + sortString;
}
debug(query);
var report = AdWordsApp.report(query);
try {
report.exportToSheet(reportSheet);
var subject = "Your " + reportType + " for " + dateRange + " for " + AdWordsApp.currentAccount().getName() + " is ready";
var body = currentSetting.ss + "<br>You can now add this data to <a href='https://www.optmyzr.com'>Optmyzr</a> or another reporting system.";
MailApp.sendEmail(EMAIL_ADDRESSES, subject, body);
Logger.log("Your report is ready at " + currentSetting.ss);
Logger.log("You can include this in your scheduled Optmyzr reports or another reporting tool.");
} catch (e) {
debug("error: " + e);
}
}
function debug(text) {
if(DEBUG) Logger.log(text);
}
I've tried overwriting the data validation in the host spreadsheet, but think I need to amend the script itself also.

Cannot remove table after callback function is called

I'm trying to remove a table after some callback functions but table rows just keep getting inserted instead. I don't understand why the table is not being removed after the callbacks. I see that it actually calls the removeTable function and it knows that the table.length is more than 1 but nothing happens. Is it too quick or is it the way I'm doing ajax?
setInterval((function() {
showLeaders();
return showLeaders;
}()), 60000);
function showLeaders() {
uri = 'leaderboard.php'
ajaxLeaders(uri, callback);
setTimeout(function() {
uri = 'leaderboard.php';
ajaxLeaders(uri, callback2);
}, 15000);
}
function removeTable() {
// var table = document.getElementsByTagName('table'), index;
// console.log('im in the removeTable func '+table.length);
// for (index = table.length - 1; index >= 0; index--) {
// table[index].parentNode.removeChild(table[index]);
// }
Array.prototype.slice.call(document.getElementsByTagName('table')).forEach(
function(item) {
item.remove();
// or item.parentNode.removeChild(item); for older browsers (Edge-)
});
}
function ajaxLeaders(uri, callback) {
// console.log('ajaxLoad: ' + uri + ' - ' + params);
var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = callback;
request.open("POST", uri, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send();
// clearTimeout(ajax_failed_timer);
// ajax_failed_timer = setTimeout(ajaxError,20000);
}
var nameArray = [];
var totalPointsArray = [];
function callback(evt) {
var tables = document.getElementsByTagName('table');
console.log(tables.length);
if (tables.length >= 1) {
console.log('should remove table cause tables more than 1');
removeTable();
}
if (evt.currentTarget.readyState == 4) {
// console.log(evt.currentTarget.responseText);
var obj = JSON.parse(evt.currentTarget.responseText);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
nameArray.push(obj[key].username);
totalPointsArray.push(obj[key].total_points);
}
}
}
var bottomLeader = '';
var leaderPoints = '';
var leadersTable = '';
leadersTable = document.createElement('table');
var leadersHTML = '';
leadersHTML = '<tr>' +
'<th>Rank</th>' +
'<th>Username</th>' +
'<th>Points</th>' +
'</tr>';
for (var i = 0; i < totalPointsArray.length; i++) {
var rank = i + 1;
var infoBarEle = document.getElementById('info-bar-js');
leadersTable.className = 'animated flipInX';
/// sort width by hightest points
var maxPoints = Math.max.apply(Math, totalPointsArray);
leadersHTML +=
'<tr>' +
'<td>' + rank + '</td>' +
'<td>' + nameArray[i] + '</td>' +
'<td>' + totalPointsArray[i] + '</td>'
'</tr>';
var leaderType = document.getElementById('leaderType');
leaderType.innerHTML = 'Fantasy Football - Weekly Winners';
document.body.className = 'animated slideInRight';
}
leadersTable.innerHTML = leadersHTML;
insertAfter(leadersTable, infoBarEle);
function callback2(evt) {
var tables = document.getElementsByTagName('table');
if (tables.length >= 1) {
removeTable();
}
if (evt.currentTarget.readyState == 4) {
// console.log(evt.currentTarget.responseText);
var obj = JSON.parse(evt.currentTarget.responseText);
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
nameArray.push(obj[key].username);
totalPointsArray.push(obj[key].total_points);
}
}
}
var bottomLeader = '';
var leaderPoints = '';
var leadersTable = '';
leadersTable = document.createElement('table');
var leadersHTML = '';
leadersHTML = '<tr>' +
'<th>Rank</th>' +
'<th>Username</th>' +
'<th>Points</th>' +
'</tr>';
for (var i = 0; i < totalPointsArray.length; i++) {
var rank = i + 1;
var infoBarEle = document.getElementById('info-bar-js');
leadersTable.className = 'animated flipInX';
/// sort width by hightest points
var maxPoints = Math.max.apply(Math, totalPointsArray);
leadersHTML +=
'<tr>' +
'<td>' + rank + '</td>' +
'<td>' + nameArray[i] + '</td>' +
'<td>' + totalPointsArray[i] + '</td>'
'</tr>';
var leaderType = document.getElementById('leaderType');
leaderType.innerHTML = 'Fantasy Football - Season Winners';
document.body.className = 'animated slideInRight';
}
leadersTable.innerHTML = leadersHTML;
insertAfter(leadersTable, infoBarEle);
}
//insertAfter function
function insertAfter(newNode, referenceNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

Add event listener that tracks event and clicked object?

I have an event listener that captures the event, but I want to also capture which item was clicked. This is my code:
$(document).ready(function () {
function shareEventHandler(evt) {
if (evt.type === 'addthis.menu.share') {
//alert(typeof (evt.data)); // evt.data is an object hash containing all event data
//alert(evt.data.service);
if (evt.data.service === "tweet") {
if (blogCollection !== null) {
if (blogCollection.length) {
var result = $.grep(blogCollection, function (item) { return evt.data.url.indexOf(item.BlogUrl) > -1 });
var newArr = [];
if (result.length == 0) {
// no item
return;
} else {
var item = result[0];
alert(item.BlogTitle);
}
}
}
xt_click(this, 'C', item.BlogXtn2 + ', [' + item.BlogParentTitle + ']::[add_this]::[tweet]::[' + item.BlogTitle + ']', 'A');
}
}
}
addthis.addEventListener('addthis.menu.share', shareEventHandler);
});
I want to pass this into shareEventHandler() so that I can get the properties and the parent objects of the addThis button that was clicked, but I'm not sure how to pass it into the function.
Edit: the entire file
addthis.init();
var blogCollection;
var pageURL = location.protocol + '//' + location.host + location.pathname;
var nameOfActiveClass = "blogCategoryActive";
var category = getUrlVars()["category"];
if (category == "" || category === undefined) {
category = "All";
}
// Retrieve blogId value
if ($(".blog-wrapper").length > 0) {
var blogId = $(".blog-wrapper").attr("data-blogid");
var blogCount = $(".blog-wrapper").attr("data-blogcount");
}
// Populate the Blog Header navigation
getHeaderBlogNavigation(blogId);
// This flag controls whether to show the View more button or not
var showViewMoreFlag = true;
// Getting the correct start index
var start = getUrlVars()["start"];
if (start == "" || start == undefined) {
start = 0;
}
if (isNaN(start)) {
start = start.replace(/\D/g, '');
}
// Getting the correct end index
var end = getUrlVars()["end"];
if (end == "" || end == undefined) {
end = blogCount;
}
/*if (isNaN(end)) {
end = end.replace(/\D/g, '');
}*/
// Popluates the initial Blog post on page load
generateBlogPosts(category, start, blogCount, blogId);
if (!showViewMoreFlag) {
$('.blog-more-posts').hide();
} else {
$('.blog-more-posts').show();
}
// This function Populates the Blog Category Navigation
function getHeaderBlogNavigation(blogId) {
var end = getUrlVars()["end"];
if (end == "" || end == undefined) {
end = blogCount;
}
if (category.toLowerCase() === "all")
{
$("#Blog-Category-Navigation").append("<li class='selected " + nameOfActiveClass + "'><a class='selected " + nameOfActiveClass + "' href='" + pageURL + "?category=All&start=0&end=" + end + "'>All</a></li>");
} else {
$("#Blog-Category-Navigation").append("<li><a href='" + pageURL + "?category=All&start=0&end=" + end + "'>All</a></li>");
}
var data = "{blogId:'" + blogId + "'}";
$.ajax({
type: "POST",
url: "/WebServices/BackedByBayer/Blog/BlogCategoryList.asmx/CategoryList",
async: false,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var categoryCollection = response.d;
//alert("success lis");
if (categoryCollection.length) {
for (var i = 0; i < categoryCollection.length; i++) {
$("#Blog-Category-Navigation").append(getHeaderNavigationHTML(categoryCollection[i], blogId));
}
}
},
error: function(res) {}
});
}
function getHeaderNavigationHTML(categoryName, blogId) {
var catName = category.replace(/\s/g, '');
var catNameFromSc = categoryName.replace(/\s/g, '');
var anchorTag = "<a class='selected " + nameOfActiveClass + "' onclick='getBlogByCategory(this,\"" + blogId + "\");' href='javascript:void(0);'>" + categoryName + "</a>";
if (catName == catNameFromSc) {
return "<li class='" + nameOfActiveClass + "'>" + anchorTag + "</li>";
}
return "<li>" + anchorTag + "</li>";
}
function generateBlogPosts(categoryString, startIndex, endIndex, blogId) {
// Increased endIndex by 1 to check if there are more items to display
var count = parseInt(endIndex) + 1;
var data = "{filterName:'" + categoryString + "', startIndex:" + startIndex + ", count: " + count + ", blogId: '" + blogId + "'}";
$.ajax({
type: "POST",
url: "/WebServices/BackedByBayer/Blog/FetchBlogPost.asmx/BlogList",
async: false,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
blogCollection = response.d;
if (blogCollection !== null) {
if (blogCollection.length) {
var numberOfBlogPosts = blogCollection.length;
if (numberOfBlogPosts == count) {
numberOfBlogPosts = numberOfBlogPosts-1;
showViewMoreFlag = true;
} else {
showViewMoreFlag = false;
}
for (var i = 0; i < numberOfBlogPosts; i++) {
var item = blogCollection[i];
$("#Blog-Posts").append(GetBlogHTML(item, i));
}
reinitiateAddThis();
}
else {
showViewMoreFlag = false;
}
} else {
showViewMoreFlag = false;
}
},
error: function (res) { }
});
}
// This function returns the HTML for individual Blog posting
function GetBlogHTML(item, i) {
var summary = item.BlogSummary;
var summarySection = "<p class='post-categories'>" + item.BlogCategoryOutput + "</p></br>" +
"<p class='post-excerpt'>" + item.BlogSummary + "</p>";
var imageSection = "";
if (item.BlogImage !== null) {
imageSection = "<div class='post-image'>" +
"<a href='" + item.BlogUrl + "' onclick=\"return xt_click(this,'C','" + item.BlogXtn2 + "','[" + item.BlogParentTitle + "]::Post Click Through::[image]:: [" + item.BlogTitle + "]','N')\" width=\"100%\">" +
"<img src='" + item.BlogImage + "' width=\"100%\" />" +
"</a>" +
"</div>";
}
var outPutHTML = "<li class='individualPost' >" +
"<article class='post'>" +
"<div class='post-details'>" +
"<h2 class='post-title'>" +
"<a href='" + item.BlogUrl + "' onclick=\"return xt_click(this,'C','" + item.BlogXtn2 + "','[" + item.BlogParentTitle + "]::Post Click Through::[headline]:: [" + item.BlogTitle + "]','N')\" >" + item.BlogListingTitle + "</a>" +
"</h2>" +
"<p class='post-date'> By: " + item.BlogAuthor + "</p>" +
"<p class='post-date'>" + item.BlogDate + "</p>" + imageSection +
summarySection +
"<footer class='post-footer'>" +
"<a href='" + item.BlogUrl + "' onclick=\"return xt_click(this,'C','" + item.BlogXtn2 + "','[" + item.BlogParentTitle + "]::Post Click Through::[read_more]:: [" + item.BlogTitle + "]','N')\" class='post-link'>Read More</a>" +
"<div class='social'>" +
"<div class='adtoolbox addthis_toolbox addthis_default_style' " +
"addthis:url='" + location.protocol + '//' + location.host + item.BlogUrl + "' addthis:title='" + item.BlogTitle + "'>" +
/*"<a class='addthis_button_facebook_like'></a>" +*/
"<a class='addthis_button_tweet'></a>" +
/*"<a class='addthis_counter addthis_pill_style'></a>" +*/
"<a style=\"background-color: rgb(115, 138, 141); margin-left: 2px; font-size: 11px; position: relative; height: 20px; padding: 1px 8px 1px 6px; font-weight: 500; color: #fff;cursor: pointer;" +
"border-radius: 3px; box-sizing: border-box; display: inline-block; vertical-align: top; zoom: 1; white-space: nowrap;\"" +
"class='addthis_button_email'>" +
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" viewBox=\"0 0 32 32\" title=\"Email\" alt=\"Email\" style=\"width: 16px; height: 16px;\" class=\"at-icon at-icon-email\"><g><path d=\"M26.19 9.55H6.04l10.02 7.57 10.13-7.57zM16.06 19.67l-10.28-8.8v11.58h20.57V10.96l-10.29 8.71z\"></path></g></svg>" +
"<span style=\"display: inline-block; vertical-align: top; padding-top:2px;\">Email</span></a></div>" +
"</div>" +
"</footer>" +
"</div>" +
"</article></li>";
return outPutHTML;
}
// Read a page's GET URL variables and return them as an associative array.
function getUrlVars() {
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
function getParameterByName(name, url) {
if (!url) url = window.location.href;
url = url.toLowerCase(); // This is just to avoid case sensitiveness
name = name.replace(/[\[\]]/g, "\\$&").toLowerCase();// This is just to avoid case sensitiveness for query parameter name
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function reinitiateAddThis() {
var script = '//s7.addthis.com/js/300/addthis_widget.js#domready=1';
if (window.addthis) {
window.addthis = null;
window._adr = null;
window._atc = null;
window._atd = null;
window._ate = null;
window._atr = null;
window._atw = null;
}
$.getScript(script);
}
// View more binding on click to fetch new blog posts
$(".blog-more-posts").click(function () {
var category = getUrlVars()["category"];
if (category == "" || category == undefined) {
category = "All";
}
var defaultNewBlogCount = 3;
//Add one to line up index
var newEnd = parseInt(end) + defaultNewBlogCount;
generateBlogPosts(category, end, defaultNewBlogCount, blogId);
end = newEnd;
if (!showViewMoreFlag) {
$('.blog-more-posts').hide();
}
if (addthis !== null) {
addthis.toolbox('.adtoolbox');
}
reinitiateAddThis();
});
// This function is called when we click on the Navigation links for Categories
function getBlogByCategory(element, blogId) {
var categoryName = $(element).text();
var catNameFromSc = $(element).text().replace(/\s/g, '');
var end = getUrlVars()["end"];
if (end == undefined) {
end = blogCount;
}
// Changes the URL of the page without reload
window.History.pushState('page 2', 'Blog Listing - ' + categoryName, pageURL + "?category=" + catNameFromSc + "&start=0&end="+end);
// Changing the Active class
jQuery("li").each(function () {
jQuery(this).removeClass(nameOfActiveClass);
});
jQuery(element).closest('li').addClass(nameOfActiveClass);
// Fetching new Start and end index
var start = getUrlVars()["start"];
if (start == undefined) {
start = 0;
}
start = start.replace(/\D/g, '');
// Setting the page with new Data
// Emptying the blog post from previous Category
$('#Blog-Posts').empty();
$('.blog-more-posts').hide();
generateBlogPostsOnCategoryClick(catNameFromSc, start, end, blogId);
if (!showViewMoreFlag) {
$('.blog-more-posts').hide();
} else {
$('.blog-more-posts').show();
}
}
// This function is called when we click on the Navigation links for Categories
function generateBlogPostsOnCategoryClick(categoryString, startIndex, endIndex, blogId) {
// Increased endIndex by 1 to check if there are more items to display
var count = parseInt(endIndex) + 1;
var data = "{filterName:'" + categoryString + "', startIndex:" + startIndex + ", count: " + count + ", blogId: '" + blogId + "'}";
$.ajax({
type: "POST",
url: "/WebServices/BackedByBayer/Blog/FetchBlogPost.asmx/BlogList",
async: false,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var blogCollection = response.d;
if (blogCollection !== null) {
if (blogCollection.length) {
var numberOfBlogPosts = blogCollection.length;
if (numberOfBlogPosts == count) {
numberOfBlogPosts = numberOfBlogPosts-1;
showViewMoreFlag = true;
} else {
showViewMoreFlag = false;
}
for (var i = 0; i < numberOfBlogPosts; i++) {
var item = blogCollection[i];
$("#Blog-Posts").append(GetBlogHTML(item, i));
if (addthis !== null) {
addthis.toolbox('.adtoolbox');
}
}
}
else {
showViewMoreFlag = false;
}
} else {
showViewMoreFlag = false;
}
reinitiateAddThis();
}
});
}
//Analytics for add this
$(document).ready(function () {
function shareEventHandler(evt) {
if (evt.type === 'addthis.menu.share') {
//alert(typeof (evt.data)); // evt.data is an object hash containing all event data
//alert(evt.data.service);
if (evt.data.service === "tweet") {
var x = this;
if (blogCollection !== null) {
if (blogCollection.length) {
var result = $.grep(blogCollection, function (item) { return evt.data.url.indexOf(item.BlogUrl) > -1 });
var newArr = [];
for (var i = 0; i < blogCollection.length; i++) {
var blogItem = blogCollection[i];
if (evt.data.url.indexOf(blogItem.BlogUrl) > -1) {
newArr.push(blogItem);
}
}
if (result.length == 0) {
// no item
return;
} else {
var item = result[0];
}
}
}
xt_click(this, 'C', item.BlogXtn2 + ', [' + item.BlogParentTitle + ']::[add_this]::[tweet]::[' + item.BlogTitle + ']', 'A');
}
}
}
addthis.addEventListener('addthis.menu.share', shareEventHandler.bind(addthis));
});
I believe you are looking for event.target:
A reference to the object that dispatched the event.
In your case, that would be evt.target
Erica,
If I'm understanding you question, I believe you may just want to bind(this) on your addEventListener and then you should be able to access the context in which the addThis button was clicked.
addthis.addEventListener('addthis.menu.share', shareEventHandler.bind(addthis));
Maybe reading https://msdn.microsoft.com/en-us/library/dn569317(v=vs.94).aspx will help.

A number is converted to NaN after some clicked to show in console - Jquery

I'm making a paging on list of products. When i clicked on "Next" button and show in console value of "tranght" (My code only show value of "tranght") then type of "tranght" is converted to NaN. Help me, i'm newer in Jquery.
<script type="text/javascript"
src="${pageContext.request.contextPath }/js/jquery-1.6.2.js"></script>
<script type="text/javascript">
var ds = [];
var tranght = 1;
var sobanghi = 0;
var sotrang = 0;
$(document).ready(function(){
$('#btnshow').click(function(){
$.ajax({
type : 'GET',
headers : {
Accept : "application/json; charset=utf-8",
"Content-Type" : "application/json; charset=utf-8"
},
url : '${pageContext.request.contextPath }/findall.html',
success : function(result) {
ds = result.dssp;
sobanghi = result.dssp.length;
if ((sobanghi % 3) === 0){
sotrang = Math.floor(sobanghi / 3);
} else {
sotrang = Math.floor(sobanghi / 3) + 1;
}
var s = "";
s = s + "<table border=\"1\"><tr class=\"title\"><td>Ma sp</td><td>Ten sp</td><td>Gia</td><td>So luong</td><td>Ngay sx</td><td>Tinh trang</td><td>Mo ta</td><td>Hinh anh</td><td>Danh muc</td></tr>";
for (var i=0; i<3; i++){
s = s + "<tr><td>" + result.dssp[i].masp + "</td><td>" + result.dssp[i].tensp + "</td><td>" + result.dssp[i].gia + "</td><td>"+ result.dssp[i].soluong +"</td><td>"+ result.dssp[i].ngaysx + "</td><td>"+ result.dssp[i].tinhtrang +"</td><td>"+ result.dssp[i].mota +"</td><td>"+ result.dssp[i].hinhanh +"</td><td>"+ result.dssp[i].danhmuc.tendm +"</td></tr>" ;
}
s = s + "</table>";
$('#result').html(s);
var s1 = "<div class='prev'>Prev</div>";
s1 += "<div class='index clicked'>" + 1 + "</div>";
for (var i=2; i<=sotrang; i++){
s1 += "<div class='index'>" + i + "</div>";
}
s1 += "<div class='next'>Next</div>";
$('#result1').html(s1);
}
});
});
//select a page
$(".index").live('click', function(){
$("#result1 > div").removeClass('clicked');
$(this).addClass('clicked');
tranght = parseInt($(this).html());
var startpoint = (tranght - 1)*3;
var endpoint = startpoint + 3;
sobanghi = ds.length
if (endpoint > sobanghi){
endpoint = sobanghi;
}
var s = "";
s = s + "<table border=\"1\"><tr class=\"title\"><td>Ma sp</td><td>Ten sp</td><td>Gia</td><td>So luong</td><td>Ngay sx</td><td>Tinh trang</td><td>Mo ta</td><td>Hinh anh</td><td>Danh muc</td></tr>";
for (var i=startpoint; i<endpoint; i++){
s = s + "<tr><td>" + ds[i].masp + "</td><td>" + ds[i].tensp + "</td><td>" + ds[i].gia + "</td><td>"+ ds[i].soluong +"</td><td>"+ ds[i].ngaysx + "</td><td>"+ ds[i].tinhtrang +"</td><td>"+ ds[i].mota +"</td><td>"+ ds[i].hinhanh +"</td><td>"+ ds[i].danhmuc.tendm +"</td></tr>" ;
}
s = s + "</table>";
$('#result').html(s);
});
// click "next" button
$(".next").live('click', function(){
console.log("value of tranght: " + tranght);
console.log("Type of: " + typeof tranght);
if (tranght === sotrang){
tranght = sotrang;
console.log("Type of: " + typeof tranght);
} else {
tranght = parseInt(tranght,6) + 1;
console.log("value: " + tranght);
console.log("Type of: " + typeof tranght);
}
});
});
</script>
We are missing some code, is the html object with the class 'index' an input? if so, you need to change
tranght = parseInt($(this).html());
to
tranght = parseInt($(this).val());
to capture the value and not the content.

image upload not working when changing upload button from input to span

I have the following image upload script:
function upload_media_async(form_name, media_type, file_path, file_url, file_embed, nb_uploads, max_uploads, upload_id) {
var radio_buttons = [];
for (var i = 0; i < form_name.length; i++) {
if (form_name.elements[i].type == 'radio' && form_name.elements[i].checked == true) {
radio_buttons[form_name.elements[i].name] = form_name.elements[i].value;
}
}
var jsHttp = new JsHttpRequest();
var xmlHttp = GetXmlHttpObject();
if (jsHttp == null) {
alert("Browser does not support HTTP Request");
return;
}
var media_name = '';
switch (media_type) {
case 1:
media_name = 'ad_image';
break;
case 2:
media_name = 'ad_video';
break;
case 3:
media_name = 'ad_dd';
break;
}
var media_box_name = 'display_media_boxes_' + media_name;
file_embed = base64Encode(file_embed);
var url = relative_path + 'ajax_files/upload_file.php';
var action = url + '?do=add&media_type=' + media_type + '&file_url=' + file_url +
'&file_embed=' + file_embed + '&nb_uploads=' + nb_uploads + '&upload_id=' + upload_id;
var thumbnail_div = document.getElementById('display_media_boxes_' + media_name);
var new_content = document.createElement('div');
if (file_embed != '') {
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var response = xmlHttp.responseText;
var results = response.split('|');
if (results[5] != '') {
alert(results[5]);
}
else {
new_content.innerHTML = results[3];
while (new_content.firstChild) {
thumbnail_div.appendChild(new_content.firstChild);
}
var hidden_div = document.getElementById('hidden_media_boxes');
var hidden_content = document.createElement('div');
hidden_content.innerHTML = '<input type="hidden" name="' + results[1] + '[]" id="hidden_' + results[2] + '" value="' + results[4] + '">';
while (hidden_content.firstChild) {
hidden_div.appendChild(hidden_content.firstChild);
}
nb_uploads++;
}
// document.getElementById('div_file_' + media_type).innerHTML = document.getElementById('div_file_' + media_type).innerHTML;
document.getElementById('item_file_url_' + media_type).value = '';
document.getElementById('item_file_embed_' + media_type).value = '';
if (nb_uploads >= max_uploads) {
document.getElementById('btn_upload_' + media_type).disabled = true;
document.getElementById('item_file_upload_' + media_type).disabled = true;
document.getElementById('item_file_url_' + media_type).disabled = true;
document.getElementById('item_file_embed_' + media_type).disabled = true;
}
document.getElementById('nb_uploads_' + media_type).value = nb_uploads;
}
};
xmlHttp.open("POST", action, true);
xmlHttp.send(null);
}
else {
jQuery.blockUI({message: '<p style="padding: 10px; font-size: 16px; font-family: Verdana, Arial, Helvetica, sans-serif; font-weight: bold;">' + upl_progress_msg + '</p>'});
var image_loading = document.createElement('div');
image_loading.innerHTML = '<img src="' + relative_path + 'images/loading-media.gif">';
thumbnail_div.appendChild(image_loading);
jsHttp.onreadystatechange = function() {
if (jsHttp.readyState == 4) {
var response = jsHttp.responseText;
var results = response.split('|');
if (results[5] != '') {
alert(results[5]);
thumbnail_div.removeChild(image_loading);
setTimeout(jQuery.unblockUI, 500);
}
else {
new_content.innerHTML = results[3];
while (new_content.firstChild) {
thumbnail_div.replaceChild(new_content.firstChild, image_loading);
}
setTimeout(jQuery.unblockUI, 500);
var hidden_div = document.getElementById('hidden_media_boxes');
var hidden_content = document.createElement('div');
hidden_content.innerHTML = '<input type="hidden" name="' + results[1] + '[]" id="hidden_' + results[2] + '" value="' + results[4] + '">';
while (hidden_content.firstChild) {
hidden_div.appendChild(hidden_content.firstChild);
}
nb_uploads++;
}
// document.getElementById('div_file_' + media_type).innerHTML = document.getElementById('div_file_' + media_type).innerHTML;
document.getElementById('item_file_url_' + media_type).value = '';
document.getElementById('item_file_embed_' + media_type).value = '';
if (nb_uploads >= max_uploads) {
document.getElementById('btn_upload_' + media_type).disabled = true;
document.getElementById('item_file_upload_' + media_type).disabled = true;
document.getElementById('item_file_url_' + media_type).disabled = true;
document.getElementById('item_file_embed_' + media_type).disabled = true;
}
document.getElementById('nb_uploads_' + media_type).value = nb_uploads;
for (var i = 0; i < form_name.length; i++) {
if (form_name.elements[i].type == 'radio' && radio_buttons[form_name.elements[i].name] == form_name.elements[i].value) {
form_name.elements[i].checked = true;
}
}
}
};
jsHttp.open("POST", action, true);
jsHttp.send({file: file_path});
}
}
This works fine when using this HTML:
<div id="div_file_1">
<input name="item_file_upload_1" id="item_file_upload_1" style="width: 250px;"
onchange="upload_media_async(ad_create_form, 1,
this.form.item_file_upload_1,
document.getElementById('item_file_url_1').value,
document.getElementById('item_file_embed_1').value,
document.getElementById('nb_uploads_1').value,
5,
'A_571');" type="file">
</div>
Now, I am wrapping the INPUT in a SPAN in order to style it:
<div id="div_file_1">
<span class="btn btn-file" name="item_file_upload_1"
id="item_file_upload_1" style="width: 250px;"
onchange="upload_media_async(ad_create_form, 1,
this.form.item_file_upload_1,
document.getElementById('item_file_url_1').value,
document.getElementById('item_file_embed_1').value,
document.getElementById('nb_uploads_1').value,
5,
'A_571');">
<input type="file">
</span>
</div>
And suddenly the upload doesn't work anymore. When I click to select a file, it does nothing ...it just sits there. What do I have to change in order to make it work even with the SPAN wrapped around the INPUT?
In this.form.item_file_upload_1, this refers to the span. Therefore this.form is undefined. We need to access the form another way. You'll also need to move the name and id back to their <input>. That should get you on the right path.

Categories