Variable scope issue using Chart.Js - javascript

I am using Chart.js in order to render multiple charts in my application.
In each chart I am using a dropdown button with different users and on selection it update the chart. Each chart come with explanations:
model_content = {
0:["fpeofko"+ fName + "fdpfokvf", "fpeofko"+ fName + "fdpfokvf" ],
1:["fpeofko"+ fName + "fdpfokvf","fpeofko"+ fName + "fdpfokvf"],
2:["fpeofko"+ fName + "fdpfokvf","fpeofko"+ fName + "fdpfokvf"],
3:["fpeofko"+ fName + "fdpfokvf","fpeofko"+ fName + "fdpfokvf"]
}
$(".pick-chart").change(function(e) {
e.preventDefault();
var val = $(this).val();
if (val != 0) {
info_process.data.datasets[1].data = info_array[val];
info_process.update();
var name2 = $('option[value='+val+']').text();
var fName = name2.split(' ')[0];
$("#ops-info").empty()
$("#dif-info").empty()
$("#info-head").empty()
ops = opposed_model[val]
dif = differ_model[val]
$("#info-head").append(" with "+ fName);
for(var x = 0; x < ops.length; x++){
text_content = model_content[ops[x]]
if (ops[x] <= 5){
if (complete[ops[x]] > 0){
inner_text_content = text_content[0];
} else {
inner_text_content = text_content[1];
}
$("#ops-info").append(
"<div class='collapsediv' data-toggle='collapse' href='#collapseExample" + ops[x] + "' + 'role=button' aria-expanded='false' aria-controls='collapseExample'>"
+ complete_label[ops[x]] + "<img src='{% static 'images/expand.png' %}' class='float-right'>" + "</div>"+
"<div class='collapse' id='collapseExample" + ops[x]+ "'" + "'><div class='card card-body'>"+ inner_text_content +"</div></div>"
);
}
}
for(var x = 0; x < dif.length; x++){
text_content = model_content[ops[x]]
if (dif[x] <= 5){
if (complete[ops[x]] > 0){
inner_text_content = text_content[0];
} else {
inner_text_content = text_content[1];
}
$("#dif-info").append(
"<div class='collapsediv' data-toggle='collapse' href='#collapseExample" + dif[x] + "' + 'role=button' aria-expanded='false' aria-controls='collapseExample'>"
+ complete_label[dif[x]] + "<img src='{% static 'images/expand.png' %}' class='float-right'>" + "</div>"+
"<div class='collapse' id='collapseExample" + dif[x]+ "'" + "'><div class='card card-body'>"+ inner_text_content +"</div></div>"
);
}
}
} else {
info_process.data.datasets[1].data = [];
$("#info-head").empty()
if (document.getElementById("ops-info") !== null){
document.getElementById("ops-info").innerHTML = "";
}
if (document.getElementById("dif-info") !== null){
document.getElementById("dif-info").innerHTML = "";
}
}
info_process.update();
});
I would like to be able in my model_content to show the name of the user selected which is stored in fName. The thing is since it is outside of my function, it is out of scope.
I could put model_content within the function but I have many charts so it would mean copying/pasting model_content many time ..
edit:
function modelContent(fName){
model_content = {
0:["fpeofko"+ fName + "fdpfokvf", "fpeofko"+ fName + "fdpfokvf" ],
1:["fpeofko"+ fName + "fdpfokvf","fpeofko"+ fName + "fdpfokvf"],
2:["fpeofko"+ fName + "fdpfokvf","fpeofko"+ fName + "fdpfokvf"],
3:["fpeofko"+ fName + "fdpfokvf","fpeofko"+ fName + "fdpfokvf"]
}
return model_content
}

Related

how to create a element to load the json data in a loop using only javascript

i want to display the theaters like a child node element of the demo node and after i want to trigger the onclick event for other function using only JavaScript
how to use foreach for creating html dom for each array in json data
i want it display like this
<div id="demo">
<div>theater in vizag</div>
<div>sangam : 4K,DolbyAtmos</div>
<div>sarat : 4K,DolbyAtmos</div>
<div>melody : 4K,DolbyAtmos</div>
</div>
let VizagData = '{"theater":[' +
'{"TheaterName":"sangam","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"sarat","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"melody","Quality":"4K","sound":"DolbyAtmos"}]}';
let VZMData = '{"theater":[' +
'{"TheaterName":"Srikanya","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"kameswari","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"IMAX","Quality":"4K","sound":"DolbyAtmos"}]}';
function search() {
document.getElementById('th').innerHTML = myfunction();
function myfunction() {
var value = document.getElementById('ct').value;
var th1 = document.createElement('div');
document.getElementById('th').appendChild(th1);
th1.innerHTML = "theaters in " + value;
return th1.innerHTML;
}
}
function data() {
var index = document.getElementById('ct');
var demo = document.getElementById("demo");
if(index.value === "vizag"){
const obj = JSON.parse(VizagData);
demo.innerHTML = obj.theater[0].TheaterName + " : " + obj.theater[0].Quality + "," + obj.theater[0].sound + "<br>" + obj.theater[1].TheaterName + " : " + obj.theater[1].Quality + "," + obj.theater[1].sound + "<br>" + obj.theater[2].TheaterName + " : " + obj.theater[2].Quality + "," + obj.theater[2].sound;
}
else {
const obj = JSON.parse(VZMData);
demo.innerHTML = obj.theater[0].TheaterName + " : " + obj.theater[0].Quality + "," + obj.theater[0].sound + "<br>" + obj.theater[1].TheaterName + " : " + obj.theater[1].Quality + "," + obj.theater[1].sound + "<br>" + obj.theater[2].TheaterName + " : " + obj.theater[2].Quality + "," + obj.theater[2].sound;
}
}
var go = document.getElementById('go');
addEventListener('click', search);
addEventListener('click', data);
<select id="ct">
<option value="vizianagaram">vizianagaram</option>
<option value="vizag">vizag</option>
</select>
<button id="go">GO</button>
<div class="th" id="th"></div>
<div id="demo"></div>
Iterate over the data and build the innerHTML. Something like:
let VizagData = '{"theater":[' +
'{"TheaterName":"sangam","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"sarat","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"melody","Quality":"4K","sound":"DolbyAtmos"}]}';
let VZMData = '{"theater":[' +
'{"TheaterName":"Srikanya","Quality":"4K","sound":"DolbyAtmos" },' +
'{"TheaterName":"kameswari","Quality":"4K","sound":"DolbyAtmos" },'+
'{"TheaterName":"IMAX","Quality":"4K","sound":"DolbyAtmos"}]}';
function search() {
document.getElementById('th').innerHTML = myfunction();
function myfunction() {
var value = document.getElementById('ct').value;
var th1 = document.createElement('div');
document.getElementById('th').appendChild(th1);
th1.innerHTML = "theaters in " + value;
return th1.innerHTML;
}
}
function data() {
var index = document.getElementById('ct');
var demo = document.getElementById("demo");
var theatres = JSON.parse(VZMData);
if(index.value === "vizag"){
theatres = JSON.parse(VizagData);
}
var innerHTML = "";
for (var obj of theatres.theater) {
innerHTML += "<div>" + obj.TheaterName + " : " + obj.Quality + "," + obj.sound + "</div>";
}
demo.innerHTML = innerHTML;
}
var go = document.getElementById('go');
addEventListener('click', search);
addEventListener('click', data);
<select id="ct">
<option value="vizianagaram">vizianagaram</option>
<option value="vizag">vizag</option>
</select>
<button id="go">GO</button>
<div class="th" id="th"></div>
<div id="demo"></div>

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.

Cancel one file to upload jQuery

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.

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.

Categories