How to add link to this javascript? - javascript

This is the full javascript for read more link of post summary-
<script type='text/javascript'>
//<![CDATA[
function removeHtmlTag(strx,chop){
if(strx.indexOf("<")!=-1)
{
var s = strx.split("<");
for(var i=0;i<s.length;i++){
if(s[i].indexOf(">")!=-1){
s[i] = s[i].substring(s[i].indexOf(">")+1,s[i].length);
}
}
strx = s.join("");
}
chop = (chop < strx.length-1) ? chop : strx.length-2;
while(strx.charAt(chop-1)!=' ' && strx.indexOf(' ',chop)!=-1) chop++;
strx = strx.substring(0,chop-1);
return strx+'...';
}
function createSummaryAndThumb(pID){
var div = document.getElementById(pID);
var imgtag = "";
var img = div.getElementsByTagName("img");
var summ = summary_noimg;
if(thumbnail_mode == "yes") {
if(img.length>=1) {
imgtag = '<span style="float:left; padding-right:10px;"><img src="'+img[0].src+'" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/></span>';
summ = summary_img;
}
}
var summary = imgtag + '<div>' + removeHtmlTag(div.innerHTML,summ) + '</div>';
div.innerHTML = summary;
}
//]]>
</script>
In var summary i tried to add a link like <a href='http://xyz.com'>read more</a> in this way
var summary = imgtag + '<div>' + removeHtmlTag(div.innerHTML,summ) + '<a href='http://xyz.com'>' + '<span>' + readmore + '</span>' + '</a>' + '</div>';
But this is not working. I know little bit javascript. Please help me.

Related

Excel warning when opening .xls exported table with javascript

I am using a script that exports a content of a pivot table to a .xls excel file. The problem is that everytime that I open this file, Excel gives the following warning message, although it successfully opens it:
"The file you are trying to open, '[filename]', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?"
Is there a way to export the file without having this warning?
I am using orb.js. The javascript code that exports is below:
function(_dereq_, module, exports) {
var utils = _dereq_('./orb.utils');
var uiheaders = _dereq_('./orb.ui.header');
var themeManager = _dereq_('./orb.themes');
var uriHeader = 'data:application/vnd.ms-excel;base64,';
var docHeader = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">' +
'<head>' +
'<meta http-equiv=Content-Type content="text/html; charset=UTF-8">' +
'<!--[if gte mso 9]><xml>' +
' <x:ExcelWorkbook>' +
' <x:ExcelWorksheets>' +
' <x:ExcelWorksheet>' +
' <x:Name>###sheetname###</x:Name>' +
' <x:WorksheetOptions>' +
' <x:ProtectContents>False</x:ProtectContents>' +
' <x:ProtectObjects>False</x:ProtectObjects>' +
' <x:ProtectScenarios>False</x:ProtectScenarios>' +
' </x:WorksheetOptions>' +
' </x:ExcelWorksheet>' +
' </x:ExcelWorksheets>' +
' <x:ProtectStructure>False</x:ProtectStructure>' +
' <x:ProtectWindows>False</x:ProtectWindows>' +
' </x:ExcelWorkbook>' +
'</xml><![endif]-->' +
'</head>' +
'<body>';
var docFooter = '</body></html>';
module.exports = function(pgridwidget) {
var config = pgridwidget.pgrid.config;
var currTheme = themeManager.current();
currTheme = currTheme === 'bootstrap' ? 'white' : currTheme;
var override = currTheme === 'white';
var buttonTextColor = override ? 'black' : 'white';
var themeColor = themeManager.themes[currTheme];
var themeFadeout = themeManager.utils.fadeoutColor(themeColor, 0.1);
var buttonStyle = 'style="font-weight: bold; color: ' + buttonTextColor + '; background-color: ' + themeColor + ';" bgcolor="' + themeColor + '"';
var headerStyle = 'style="background-color: ' + themeFadeout + ';" bgcolor="' + themeFadeout + '"';
function createButtonCell(caption) {
return '<td ' + buttonStyle + '><font color="' + buttonTextColor + '">' + caption + '</font></td>';
}
function createButtons(buttons, cellsCountBefore, cellsCountAfter, prefix) {
var i;
var str = prefix || '<tr>';
for (i = 0; i < cellsCountBefore; i++) {
str += '<td></td>';
}
str += buttons.reduce(function(tr, field) {
return (tr += createButtonCell(field.caption));
}, '');
for (i = 0; i < cellsCountAfter; i++) {
str += '<td></td>';
}
return str + '</tr>';
}
var cellsHorizontalCount = Math.max(config.dataFields.length + 1, pgridwidget.layout.pivotTable.width);
var dataInicioFilter = (pgridwidget.pgrid.config.dataInicio==null) ? '' :
'<tr><td><font color=\"#ccc\">Data Início</font></td>' + '<td ' + buttonStyle +
'><font color="' + buttonTextColor + '">' + pgridwidget.pgrid.config.dataInicio +
'</font></td>'+'</tr>';
var dataFimFilter = (pgridwidget.pgrid.config.dataFim==null) ? '' :
'<tr><td><font color=\"#ccc\">Data Fim</font></td>' + '<td ' + buttonStyle +
'><font color="' + buttonTextColor + '">' + pgridwidget.pgrid.config.dataFim +
'</font></td>'+'</tr>';
var comissaoFilter = (pgridwidget.pgrid.config.comissao==0) ? '' :
'<tr><td><font color=\"#ccc\">Comissão (R$)</font></td>' + '<td ' + buttonStyle +
'><font color="' + buttonTextColor + '">' + pgridwidget.pgrid.config.comissao +
'</font></td>'+'</tr>';
var dataFields = createButtons(config.dataFields,
0,
cellsHorizontalCount - config.dataFields.length,
'<tr><td><font color="#3a2c2c">Dados</font></td>'
);
var sep = '<tr><td style="height: 22px;" colspan="' + cellsHorizontalCount + '"></td></tr>';
var columnFields = createButtons(config.columnFields,
pgridwidget.layout.rowHeaders.width,
cellsHorizontalCount - (pgridwidget.layout.rowHeaders.width + config.columnFields.length)
);
var columnHeaders = (function() {
var str = '';
var j;
for (var i = 0; i < pgridwidget.columns.headers.length; i++) {
var currRow = pgridwidget.columns.headers[i];
var rowStr = '<tr>';
if (i < pgridwidget.columns.headers.length - 1) {
for (j = 0; j < pgridwidget.layout.rowHeaders.width; j++) {
rowStr += '<td></td>';
}
} else {
rowStr += config.rowFields.reduce(function(tr, field) {
return (tr += createButtonCell(field.caption));
}, '');
}
rowStr += currRow.reduce(function(tr, header) {
var value = header.type === uiheaders.HeaderType.DATA_HEADER ? header.value.caption : header.value;
return (tr += '<td ' + headerStyle + ' colspan="' + header.hspan(true) + '" rowspan="' + header.vspan(true) + '">' + value + '</td>');
}, '');
str += rowStr + '</tr>';
}
return str;
}());
var rowHeadersAndDataCells = (function() {
var str = '';
var j;
for (var i = 0; i < pgridwidget.rows.headers.length; i++) {
var currRow = pgridwidget.rows.headers[i];
var rowStr = '<tr>';
rowStr += currRow.reduce(function(tr, header) {
return (tr += '<td ' + headerStyle + ' colspan="' + header.hspan(true) + '" rowspan="' + header.vspan(true) + '">' + header.value + '</td>');
}, '');
var dataRow = pgridwidget.dataRows[i];
rowStr += dataRow.reduce(function(tr, dataCell, index) {
var formatFunc = config.dataFields[index = index % config.dataFields.length].formatFunc;
var value = dataCell.value == null ? '' : formatFunc ? formatFunc()(dataCell.value) : dataCell.value;
return (tr += '<td>' + value + '</td>');
}, '');
str += rowStr + '</tr>';
}
return str;
}());
function toBase64(str) {
return utils.btoa(unescape(encodeURIComponent(str)));
}
return uriHeader +
toBase64(docHeader +
'<table>' + dataInicioFilter + dataFimFilter + comissaoFilter + dataFields + sep + columnFields + columnHeaders + rowHeadersAndDataCells + '</table>' +
docFooter);
};
}

Wordpress API - on click permalink - get single post and display

Like to get single post WP API on click and replace it inside main div newsPostsContainer - kind of like routing.
I am successfully displaying a list of posts from an external source.
If anyone can help with my code or recommend another library/client with example to do exactly this that would be great.
Heres my code.
window.onload = function(){
var newsPermalink = document.getElementById("news-Permalink");
var newsPostsContainer = document.getElementById("news-Posts-Container");
var externalDomain = "http://example.com";
var newDomain = "http://localhost.dev";
//----------------- WP API - News Content ------------------//
var newsRequest = new XMLHttpRequest();
newsRequest.open('GET', externalDomain + '/wp-json/wp/v2/posts?
filter[category_name]=news-and-events&?per_page=5&_embed=true');
function createNEWS(postsData){
var ourHTMLString = '';
for (i = 0;i < postsData.length;i++){
var title = postsData[i].title.rendered;
var newsHref = postsData[i].link;
var newsHrefOutput = newsHrefOutput.replace(externalDomain, newDomain);
if(postsData[i].featured_image_src !== externalDomain + "/wp-includes/images/media/default.png"){
ourHTMLString += '<a id="news-Permalink" href="'+newsHrefOutput+'" title="'+title+'"><img class="img-responsive pull-left news-thumbnail-lg wp-post-image" src=' + postsData[i].featured_image_src + '></a><br>';
}
ourHTMLString += '<a id="news-Permalink" href="'+newsHref+'" title="'+title+'"><h6 class="news-title">' + postsData[i].title.rendered + '</h6></a>' ;
ourHTMLString += postsData[i].excerpt.rendered + '...<br><br>';
}
newsPostsContainer.innerHTML = ourHTMLString;
}
newsRequest.onload = function() {
if (newsRequest.status >= 200 && newsRequest.status < 400) {
var data = JSON.parse(newsRequest.responseText);
createNEWS(data);
} else {
console.log("News Request - We connected to the server, but it returned an error.");
}
};
newsRequest.onerror = function() {
console.log("Connection error");
};
newsRequest.send();
//All works up to here
//??
if (newsPermalink) {
newsPermalink.addEventListener("click", function() {
console.log("clicked");
newsPostsContainer.innerHTML = "";
var singlePostString = '';
if(postsData.featured_image_src !== externalDomain + "/wp-includes/images/media/default.png"){
singlePostString += '<img alt="'+title+'" class="img-responsive pull-left news-thumbnail-lg wp-post-image" src=' + postsData.featured_image_src + '><br>';
}
singlePostString += '<h6 class="news-title">' + postsData.title.rendered + '</h6>';
singlePostString += postsData.content.rendered + '<br>';
newsPostsContainer.innerHTML = singlePostString;
});
}
};//end window onload
On this part of the code:
if (newsPermalink) {
newsPermalink.addEventListener("click", function() {
console.log("clicked");
newsPostsContainer.innerHTML = "";
var singlePostString = '';
if(postsData.featured_image_src !== externalDomain + "/wp-includes/images/media/default.png"){
singlePostString += '<img alt="'+title+'" class="img-responsive pull-left news-thumbnail-lg wp-post-image" src=' + postsData.featured_image_src + '><br>';
}
singlePostString += '<h6 class="news-title">' + postsData.title.rendered + '</h6>';
singlePostString += postsData.content.rendered + '<br>';
newsPostsContainer.innerHTML = singlePostString;
});
}
What would postsData be referencing to? I'd say it's failing here because postsData would be null and it would cause an undefined error.
If you want it to work, then you'll have to create a new variable to assign the data to when you run the createNEWS() function and then call that variable on the onClick of the permalink.
I.e
var globalPostData = "";
....
function createNEWS(postsData){
var ourHTMLString = '';
for (i = 0;i < postsData.length;i++){
var title = postsData[i].title.rendered;
var newsHref = postsData[i].link;
var newsHrefOutput = newsHref.replace(externalDomain, newDomain);
if(postsData[i].featured_image_src !== externalDomain + "/wp-includes/images/media/default.png"){
ourHTMLString += '<a id="news-Permalink" href="'+newsHref+'" title="'+title+'"><img class="img-responsive pull-left news-thumbnail-lg wp-post-image" src=' + postsData[i].featured_image_src + '></a><br>';
}
ourHTMLString += '<a id="news-Permalink" href="'+newsHref+'" title="'+title+'"><h6 class="news-title">' + postsData[i].title.rendered + '</h6></a>' ;
ourHTMLString += postsData[i].excerpt.rendered + '...<br><br>';
}
newsPostsContainer.innerHTML = ourHTMLString;
//Assign your data here
globalPostData = ourHTMLString;
}
...
//Reference your new variable on click
if (newsPermalink) {
newsPermalink.addEventListener("click", function() {
console.log("clicked");
newsPostsContainer.innerHTML = "";
var singlePostString = '';
if(globalPostData.featured_image_src !== externalDomain + "/wp-includes/images/media/default.png"){
singlePostString += '<img alt="'+title+'" class="img-responsive pull-left news-thumbnail-lg wp-post-image" src=' + postsData.featured_image_src + '><br>';
}
singlePostString += '<h6 class="news-title">' + postsData.title.rendered + '</h6>';
singlePostString += globalPostData.content.rendered + '<br>';
newsPostsContainer.innerHTML = singlePostString;
});
}

Trying to using HTML data attribute to match data from two databases

I have code below that renders a few products on a page. Each of these products shares the same data attribute "data-item-upc". There is also a button that is rendered for each product on the page (6 total buttons to be exact). They all share this same data-item-upc data attribute.
I am able to successfully grab the value of the data atrribute and match it to the item with the same UPC value in the second database. But for some reason only the first button works and shows the modal. Not sure whats going on. Hoping someone can help me out would really appreciate it.
//declare variable to store JSON data
var product_data = {};
var nutritional_data = {};
$(document).ready(function() {
'use strict';
//grab product data
$.ajax({
dataType: "jsonp",
url: 'path to URL',
cache: true,
success: function(data){
//assign JSON to product data variable
product_data = JSON.parse(JSON.stringify(data).replace(/"\s+|\s+"/g,'"'));
//grab nutrional data
$.ajax({
dataType: "jsonp",
url: 'path to URL',
cache: true,
success: function(json){
//assign JSON to product data variable
nutritional_data = JSON.parse(JSON.stringify(json).replace(/"\s+|\s+"/g,'"'));
//declare divs to store data
var productDivOne = '';
var productDivTwo = '';
$.each(product_data, function(i, item) {
//convert JSON strings to uppercase for comparison
var brandLetter = item.itemBrandLetter.toUpperCase();
var foodService = item.itemDeli.toUpperCase();
var brandItem = item.itemName;
if (brandLetter == "LB" && foodService == "N") {
if (brandItem.indexOf("Panettone") >= 0) {
productDivOne +=
'<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">' +
'<div class="thumbnail">' +
'<img class="scale-down-seperate-prods" src="' + item.imageURL + '" alt="' + item.itemName + '" />' +
'<div class="caption">' + '<br>' +
'<h3 class="group inner list-group-item-heading">' + item.itemName + '</h3>' +
'<h4 class="group inner list-group-item-text">' + item.itemFullUPC.slice(1, -1) + ' • ' + item.itemPackSize.toLowerCase().substring(item.itemPackSize.lastIndexOf("/") + 1) + '</h4>' +
'<button type="button" class="btn btn-info btn-lg showNutritionFacts" data-item-upc="' + item.itemFullUPC + '" value="itemFullUPC">Nutrition Facts</button>' +
'</div>' +
'</div>' +
'</div>';
}
if (brandItem.indexOf("Egg") >= 0) {
productDivTwo +=
'<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">' +
'<div class="thumbnail">' +
'<img class="scale-down-seperate-prods" src="' + item.imageURL + '" alt="' + item.itemName + '" />' +
'<div class="caption">' + '<br>' +
'<h3 class="group inner list-group-item-heading">' + item.itemName + '</h3>' +
'<h4 class="group inner list-group-item-text">' + item.itemFullUPC.slice(1, -1) + ' • ' + item.itemPackSize.toLowerCase().substring(item.itemPackSize.lastIndexOf("/") + 1) + '</h4>' +
'<button type="button" class="btn btn-info btn-lg showNutritionFacts" data-item-upc="' + item.itemFullUPC + '" value="itemFullUPC">Nutrition Facts</button>' +
'</div>' +
'</div>' +
'</div>';
}
}
});
//show nutritional information on button click
$("body").on('click', ".showNutritionFacts", function(event){
//get passed data from other function
var clickedItemUPC = $(this).data('item-upc');
alert(clickedItemUPC);
//declare variables to store data
var servingSize = '';
var servingPerContainer = '';
var calories = '';
var caloriesFat = '';
var totalFatGrams = '';
var totalFatPercentage = '';
var saturatedFatGrams = '';
var saturatedFatPercentage = '';
var transFatGrams = '';
var polyunsaturatedFatGrams = '';
var monounsaturatedFatGrams = '';
var cholesterolGrams = '';
var cholesterolPercentage = '';
var sodiumGrams = '';
var sodiumPercentage = '';
var totalCarbohydrateGrams = '';
var totalCarbohydratePercentage = '';
var dietaryFiberGrams = '';
var dietaryFiberPercentage = '';
var sugarGrams = '';
var sugarGramsAdded = '';
var sugarGramsAddedPercentage = '';
var proteinGrams = '';
var vitaminAPercentage = '';
var vitaminCGrams = '';
var vitaminCPercentage = '';
var vitaminDGrams = '';
var vitaminDPercentage = '';
var calciumGrams = '';
var calciumPercentage = '';
var ironGrams = '';
var ironPercentage = '';
var potassiumGrams = '';
var potassiumPercentage = '';
var thiamineGrams = '';
var thiaminePercentage = '';
var riboflavinGrams = '';
var riboflavinPercentage = '';
var niacinGrams = '';
var niacinPercentage = '';
var ingredients = '';
//comparison UPC variable
var compareNutUPC;
$.each(nutritional_data, function (i, item) {
//assign comparison UPC to itemNum
compareNutUPC = item.itemNum;
//compare product UPC in nutritional and product data
if (clickedItemUPC == compareNutUPC) {
servingSize += item.servingSize;
servingPerContainer += item.itemServings;
calories += item.itemCalories;
caloriesFat += item.itemCaloriesFromFat;
transFatGrams += item.itemTransFat + 'g';
polyunsaturatedFatGrams += item.itemPolyUnsatFat + 'g';
monounsaturatedFatGrams += item.itemMonoUnsatFat + 'g';
saturatedFatGrams += item.itemSaturFat + 'g';
saturatedFatPercentage += item.itemSaturFatPerc + '%';
totalFatGrams += item.itemTotalFat + 'g';
totalFatPercentage += item.itemTotalFatPerc + '%';
cholesterolGrams += item.itemCholesterol + 'mg';
cholesterolPercentage += item.itemCholesterolPerc + '%';
sodiumGrams += item.itemSodium + 'mg';
sodiumPercentage += item.itemSodiumPerc + '%';
totalCarbohydrateGrams += item.itemTotalCarb + 'g';
totalCarbohydratePercentage += item.itemTotalCarbPerc + '%';
sugarGrams += item.itemSugars + 'g';
sugarGramsAdded += item.itemSugarsAdded + 'g';
sugarGramsAddedPercentage += item.itemSugarsAddedPerc + '%';
dietaryFiberGrams += item.itemDietFiber + 'g';
dietaryFiberPercentage += item.itemDietFiberPerc + '%';
proteinGrams += item.itemProtein + 'g';
vitaminAPercentage += item.itemVitaminA + '%';
vitaminCPercentage += item.itemVitaminC + '%';
vitaminDGrams += item.itemVitaminDMeasure;
vitaminDPercentage += item.itemVitaminD + '%';
calciumGrams += item.itemCalciumMeasure;
calciumPercentage += item.itemCalcium + '%';
ironGrams += item.itemIronMeasure;
ironPercentage += item.itemIron + '%';
thiaminePercentage += item.itemThiamin + '%';
riboflavinPercentage += item.itemRiboflavin + '%';
niacinPercentage += item.itemNiacin + '%';
potassiumGrams += item.itemPotassium;
potassiumPercentage += item.itemPotassiumPerc + '%';
ingredients += item.itemIngredients;
}
});
$(".servingSize").html(servingSize.replace(/\s+(?=g)/g, '').toLowerCase());
$(".servingPerContainer").html(servingPerContainer);
$(".calories").html(calories);
$(".caloriesFat").html(caloriesFat);
$(".transFatGrams").html(transFatGrams);
$(".polyunsaturatedFatGrams").html(polyunsaturatedFatGrams);
$(".monounsaturatedFatGrams").html(monounsaturatedFatGrams);
$(".saturatedFatGrams").html(saturatedFatGrams);
$(".saturatedFatPercentage").html(saturatedFatPercentage);
$(".totalFatGrams").html(totalFatGrams);
$(".totalFatPercentage").html(totalFatPercentage);
$(".cholesterolGrams").html(cholesterolGrams);
$(".cholesterolPercentage").html(cholesterolPercentage);
$(".sodiumGrams").html(sodiumGrams);
$(".sodiumPercentage").html(sodiumPercentage);
$(".totalCarbohydrateGrams").html(totalCarbohydrateGrams);
$(".totalCarbohydratePercentage").html(totalCarbohydratePercentage);
$(".sugarGrams").html(sugarGrams);
$(".sugarGramsAdded").html(sugarGramsAdded);
$(".sugarGramsAddedPercentage").html(sugarGramsAddedPercentage);
$(".dietaryFiberGrams").html(dietaryFiberGrams);
$(".dietaryFiberPercentage").html(dietaryFiberPercentage);
$(".proteinGrams").html(proteinGrams);
$(".vitaminAPercentage").html(vitaminAPercentage);
$(".vitaminCPercentage").html(vitaminCPercentage);
$(".vitaminDGrams").html(vitaminDGrams);
$(".vitaminDPercentage").html(vitaminDPercentage);
$(".calciumGrams").html(calciumGrams);
$(".calciumPercentage").html(calciumPercentage);
$(".ironGrams").html(ironGrams);
$(".ironPercentage").html(ironPercentage);
$(".thiaminePercentage").html(thiaminePercentage);
$(".riboflavinPercentage").html(riboflavinPercentage);
$(".niacinPercentage").html(niacinPercentage);
$(".potassiumGrams").html(potassiumGrams);
$(".potassiumPercentage").html(potassiumPercentage);
$(".ingredients").html(ingredients.toUpperCase());
//determine which modal to show
if ($('.vitaminDGrams:contains("mcg")').length > 0 && $('.calciumGrams:contains("mg")').length > 0 && $('.ironGrams:contains("mg")').length > 0) {
$('.nutritionPopupAlternate').modal('show');
} else if (servingSize == 0) {
$('.nutritionPopupNoInfo').modal('show');
} else {
$('.nutritionPopupStandard').modal('show');
}
});
//append to appropriate div
$('#productDivOne').html(productDivOne);
$('#productDivTwo').html(productDivTwo);
}
});
//end of prod data
}
});
//end of nut data
});
Thanks to Sandy i was able to minify my code and find the issue. Turns out it was looking for something that was added later from a different source code that I took, after editing the DIV it works perfectly now.

How to create a dynamic table in jQuery?

I want to create a dynamic table in jQuery. But my code creates a table for each of my element.
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content = "<table>" + "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
Which part of my code is wrong?
as you were adding table in for loop, so it was creating table for each item.Try this:
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
content ="<table>"
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 = content;
}
content += "</table>"
// you can also assign spl2 = content; over here.
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
var str = dataItem.Description;
var spl = str.split(','), part;
var spl2 = "";
var content = "<table>";
for (var i = 0; i < spl.length; i++) {
part = spl[i].split(':');
content += "<tr><td>" + part[0] + "</td>" + "<td>" + part[1] + "</td></tr>";
spl2 += content;
}
content += "</table>"
var desc = "<div id='openModal' class='modalDialog'>" + "<span>" +
spl2
+ "</span><br/>" +
+ "</div>";
Updated your script

Undefined Variable In document.write [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
I keep getting "toggleOnlyRelatedPosts is not defined " in Chrome console and the script doesn't work. I'm working on this script and I've gotten lost after adding so many variables. I'm not that good at this sort of thing and to me it looks clearly defined, but I guess it's not. Chrome marks the error at the document.write
Here is the script:
<script type="text/javascript">
//<![CDATA[
function postGrabber(json) {
// The Magic
for (var i = 0; i < json.feed.entry.length; i++) {
for (var j = 0; j < json.feed.entry[i].link.length; j++) {
if (json.feed.entry[i].link[j].rel == 'alternate') {
var postUrl = json.feed.entry[i].link[j].href;
break;
}
}
// Thumbnail Stuff
var orgImgUrl = json.feed.entry[i].media$thumbnail.url ? json.feed.entry[i].media$thumbnail.url : 'http://1.bp.blogspot.com/-mxinHrJWpBo/VD6fqbvI74I/AAAAAAAAcn8/LslulDeOROg/s72-c/noimage-chalkboard.jpg';
var newImgUrl = orgImgUrl.replace('s72-c', 's' + imgSize + '-c');
var imgTag = '<a class="item-link-post" href="' + postUrl + '"><img class="item-img-thumbnail" src="' + newImgUrl + '" width="' + imgSize + '" height="' + imgSize + '"/></a>';
var authorName = json.feed.entry[i].author[0].name.$t;
var authorURL = json.feed.entry[i].author[0].uri.$t;
var authorOriImgUrl = json.feed.entry[i].author[0].gd$image.src;
var authorNewImgUrl = authorOriImgUrl.replace('s512-c', 's' + authorImgSize + '-c');
var authorImgTag = '<a class="item-link-author" href="' + authorURL + '" target="_blank" rel="nofollow"><img class="item-img-author" src="' + authorNewImgUrl + '" alt="' + authorName + '"/></a>';
var postLabel = json.feed.category[i].term;
var postLabelUrl = '/-/' + postLabel + '';
// Standard Stuff
var postTitle = json.feed.entry[i].title.$t;
var postCommentCount = json.feed.entry[i].thr$total.$t;
var postSummary = json.feed.entry[i].summary.$t;
var entryShort = postSummary.substring(0, '' + summaryLength + '');
var entryEnd = entryShort.lastIndexOf(" ");
var postContent = entryShort.substring(0, entryEnd) + '...';
var postDate = json.feed.entry[i].updated.$t ? json.feed.entry[i].updated.$t : json.feed.entry[i].published.$t;
var shortDate = postDate.substring(0,10);
// Let's Make Options Here
var toggleImg = showImg ? '' + imgTag + '' : '';
var toggleTitle = showTitle ? '<h1 class="item-title">' + postTitle + '</h1>' : '';
var toggleSummary = showSummary ? '<p class="item-snippet">' + postContent + '</p>' : '';
var toggleDate = showDate ? '<span class="item-date">' + shortDate + '</span>' : '';
var toggleAuthorImg = showAuthorImg ? '' + authorImgTag + '' : '';
var toggleCommentCount = showCommentCount ? '<span class="item-comment-count">' + postCommentCount + '</span>' : '';
var toggleOnlyRelatedPosts = showOnlyRelatedPosts ? '' + postLabelUrl + '' : '';
// The Output
var itemPost = '<div class="item-post"><div class="item-imgs">' + toggleImg + toggleAuthorImg + '</div>' + toggleCommentCount + '<a class="item-link" href=' + postUrl + '>' + toggleTitle + '</a>' + toggleSummary + toggleDate + '</div>';
// Let's Write It Down
document.write(itemPost);
}
}
//]]>
</script>
<script type="text/javascript">
//<![CDATA[
var imgSize = 96;
var summaryLength = 142;
var authorImgSize = 36;
var showImg = true;
var showTitle = true;
var showSummary = true;
var showDate = true;
var showAuthorImg = true;
var showCommentCount = true;
var showOnlyRelatedPosts = true;
document.write('<script type="text/javascript" src="/feeds/posts/summary' + toggleOnlyRelatedPosts + '?orderby=published&max-results=5&alt=json-in-script&callback=postGrabber"><\/script>');
//]]>
</script>
The variable toggleOnlyRelatedPosts is declared in the scope of the function postGrabber. It is therefore indeed undefined in the line with the document.write, where you try to use it.
If you wish to use those variables outside the function you have to declare them outside the function.
Read up on the concept of 'scope', it's pretty fundamental knowledge in any programming language.

Categories

Resources