I can't access nested JavaScript function in index.jsp - javascript

I have a function that is supposed to perform pagination on a table. Within that function is another function that needs to be executed when I click on the numbers in the navigation bar. The code works fine in VSCode. When I put the code in index.jsp in eclipse, the function gives the error: Uncaught ReferenceError: sort is not defined at HTMLButtonElement.onclick.
// get the table element
var table = document.getElementById("disposalTable"),
// number of rows per page
n = 5,
// number of rows of the table
rowCount = table.rows.length,
// get the first cell's tag name (in the first row)
firstRow = table.rows[0].firstElementChild.tagName,
// boolean var to check if table has a head row
hasHead = (firstRow === "TH"),
// an array to hold each row
tr = [],
// loop counters, to start count from rows[1] (2nd row) if the first row has a head tag
i,ii,j = (hasHead)?1:0,
// holds the first row if it has a (<TH>) & nothing if (<TD>)
th = (hasHead?table.rows[(0)].outerHTML:"");
// count the number of pages
var pageCount = Math.ceil(rowCount / n);
// if we had one page only, then we have nothing to do ..
if (pageCount > 1) {
// assign each row outHTML (tag name & innerHTML) to the array
for (i = j,ii = 0; i < rowCount; i++, ii++)
tr[ii] = table.rows[i].outerHTML;
// create a div block to hold the buttons
table.insertAdjacentHTML("afterend","<div id='buttons'></div");
// the first sort, default page is the first one
sort(1);
}
// ($p) is the selected page number. it will be generated when a user clicks a button
function sort(p) {
/* create ($rows) a variable to hold the group of rows
** to be displayed on the selected page,
** ($s) the start point .. the first row in each page, Do The Math
*/
var rows = th,s = ((n * p)-n);
for (i = s; i < (s+n) && i < tr.length; i++)
rows += tr[i];
// now the table has a processed group of rows ..
table.innerHTML = rows;
// create the pagination buttons
document.getElementById("buttons").innerHTML = pageButtons(pageCount,p);
// CSS Stuff
document.getElementById("id"+p).setAttribute("class","active");
}
// ($pCount) : number of pages,($cur) : current page, the selected one ..
function pageButtons(pCount,cur) {
/* this variables will disable the "Prev" button on 1st page
and "next" button on the last one */
var prevDis = (cur == 1)?"disabled":"",
nextDis = (cur == pCount)?"disabled":"",
/* this ($buttons) will hold every single button needed
** it will creates each button and sets the onclick attribute
** to the "sort" function with a special ($p) number..
*/
buttons = "<input type='button' value='<< Prev' onclick='sort("+(cur - 1)+")' "+prevDis+">";
for (i=1; i<=pCount;i++)
buttons += "<input type='button' id='id"+i+"'value='"+i+"' onclick='sort("+i+")'>";
buttons += "<input type='button' value='Next >>' onclick='sort("+(cur + 1)+")' "+nextDis+">";
return buttons;
}

I figured it out. Instead of trying to access the nested function. Put the pager code into a function. Then create an instance of the function as a variable. And call that variable every time.
For instance:
let pager = new Pager();
Then the onclick method will call pager.sort(1) or pager.sort(2) everytime.

Related

How to update instead of aggregating Google Slides when updating records in Google Sheet with Google Apps Script?

Using Google Apps Script, I generate G-Slides based on a template (first slide top left) as shown below...
...from a Google Sheet where each row has a set of attributes corresponding to its respective slide:
Furthermore, a trigger has been set to execute the Google Apps script 'On Open' (i.e. upon refreshing the document) in G-Sheet.
The script currently duplicates the first slide (the template) per rows with complete information, and feeds the variables from G-Sheet as designated in the {{brackets}} onto the template slide (i.e. the template_value matches the template_field).
function fillTemplateV3() {
// Id of the slides template
var PRESENTATION_ID = "PRESENTATION ID HERE";
// Open the presentation
var presentation = SlidesApp.openById(PRESENTATION_ID);
// Read data from the spreadsheet
var values = SpreadsheetApp.getActive().getDataRange().getValues();
// Replace template variables in the presentation with values
let hdr = values.shift()
values.forEach(row =>{
let templateSlide = presentation.getSlides()[0].duplicate()
for ( var i = 0 ; i < 4; i++){
let templateField = hdr[i]
let templateValue = row[i]
let logo = row[4]
console.log(logo)
templateSlide.replaceAllText(templateField, templateValue)
templateSlide.getShapes().forEach(s => {
if (s.getText().asString().trim() == "{{logo}}") s.replaceWithImage(logo);
});
}
}
);
}
The issue I'm having is that the script is additive, i.e. each time the script is executed it keeps on adding slides on top of those already created. I am not convinced that adding a function to delete the Slides before executing the for loop is efficient to address this issue.
How do I execute the script so that the number of slides in G-Slides correspond to the number of rows in G-Sheets? I.e. if I have 3 rows filled with information in G-Sheet, I should only have 4 slides total (counting the template slide). Right now, every-time the script executes, slides are added to the G-Slide document, so that if I add a fourth row, execute the script, and the script ran once before, I end up with 8 slides total. Instead I want to generate 4 slides, not counting the template slide.
Edited to clarify the code's objective.
I was overthinking this by a lot. I simply had to execute a for loop through my slides first, before executing the for loop to fill my G-Slide template from G-Sheets, in order to delete all slides besides the first one, which serves as my template slide:
function fillTemplate() {
// Id of the slides template
// Remember to replace this with the Id of your presentation
var PRESENTATION_ID = "YOUR PRESENTATION ID HERE";
// Open the presentation
var presentation = SlidesApp.openById(PRESENTATION_ID);
// Read data from the spreadsheet
var values = SpreadsheetApp.getActive().getDataRange().getValues();
// Replace template variables in the presentation with values
let hdr = values.shift()
var slides = presentation.getSlides();
//change i to any other index if desired
for (var i = 1; i < slides.length; i++) {
slides[i].remove()
}
values.forEach(row => {
let templateSlide = presentation.getSlides()[0].duplicate()
for (var i = 1; i < 6; i++) {
let templateField = hdr[i]
let templateValue = row[i]
let logo = row[6]
console.log(logo)
templateSlide.replaceAllText(templateField, templateValue)
templateSlide.getShapes().forEach(s => {
if (s.getText().asString().trim() == "{{logo_url}}") s.replaceWithImage(logo);
});
}
});
}
Credit to the answer of this post for helping me find a solution: How to delete slides programmatically after the nth one in google slides?

How to get checked rows' values from html table on a sidebar using GAS?

I have a table whose rows consist of 3 columns. 1º is a checkbox, 2º contains the colors and the 3º contains the hex.
As the user selects the colors desired by ticking the checkboxes, i imagine the colors being pushed into an arrat, that will be written to a cell as the user clicks on the save button.
I've borrowed this snippet from Mark, but it doesn't seem to run in my context:
var checkboxes = document.getElementsByTagName("input");
var selectedRows = [];
for (var i = 0; i < checkboxes.length; i++) {
var checkbox = checkboxes[i];
checkbox.onclick = function() {
var currentRow = this.parentNode.parentNode;
var secondColumn = currentRow.getElementsByTagName("td")[1];
selectedRows.push(secondColumn);
};
console.log(selectedRows)
}
This is the javascript part running to load and populate the table and I'm not sure where the above snippet woud go into:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
/**
* Run initializations on sidebar load.
*/
$(function() {
// Assign handler functions to sidebar elements here, if needed.
// Call the server here to retrieve any information needed to build
// the dialog, if necessary.
google.script.run
.withSuccessHandler(function (record) { //<-- with this
showRecord(record);
})
.withFailureHandler(
function(msg, element) {
showStatus(msg, $('#button-bar'));
element.disabled = false;
})
.getRecord();
});
/**
* Callback function to display a "record", or row of the spreadsheet.
*
* #param {object[]} Array of field headings & cell values
*/
function showRecord(record) {
if (record.length) {
for (var i = 0; i < record.length-1; i++) {
// Adds a header to the table
if(i==0){
$('#sidebar-record-block').append($($.parseHTML('<div class="div-table-row"><div class="div-table-header">Sel</div><div class="div-table-header">Color</div><div class="div-table-header">Hex</div></div>')));
}
// build field name on the fly, formatted field-1234
var str = '' + i;
var fieldId = 'field-' + ('0000' + str).substring(str.length)
// If this field # doesn't already exist on the page, create it
if (!$('#'+fieldId).length) {
var newField = $($.parseHTML('<div id="'+fieldId+'"></div>'));
$('#sidebar-record-block').append(newField);
}
// Replace content of the field div with new record
$('#'+fieldId).replaceWith('<div id="'+fieldId+'" class="div-table-row"></div>');
$('#'+fieldId).append('<input type="checkbox" class="div-table-td" id=CB"'+fieldId+'"name="checkBox" </input>')
.append($('<div class="div-table-td">' + record[i].heading + '</div>'))
.append('<div class="div-table-td">' + record[i].cellval + '</div>')
}
}
}
</script>
Sample of how to get the checked tickboxes an button click
Assuming all your checkboxes are tied to a row, you can loop through all checkboxes with a query selector,
access their checked status
and save the indices of those checkboxes.
Those indices will be the same as when looping through the corresponding table rows.
Sample implementing a button click event:
var saveButton = document.getElementById("myButtonId");
saveButton.onclick = function(){
var checkedRowIndices = [];
$('input[type=checkbox]').each(function( index ) {
if($(this)[0].checked{
checkedRowIndices.push(index);
}
});
};
//now get the rows with those indeices and do something with them

I'm trying to centralize my js scripts so that I can re-use on multiple pages

Example 1: I have a js script that I have in a script editor to wrap my promoted links. I want to replace this with a reference to a js script I will place in the Site Assets and passing one parameter that equals the number of links per row.
So I moved my code into the Site assets and reference it using the following and it did not seem to work. I am using a script editor. Not passing any parameters yet.
<script type="text/javascript" src="../Site%20Assets/js-enterprise/WrapPromotedLinks.js"></script>
My code in my Site Assets is:
<script type="text/javascript" src="https://code.jquery.com/jquery-1.10.2.min.js Jump "></script>
<script type="text/javascript">
$(document).ready(function () {
// Update this value to the number of links you want to show per row
var numberOfLinksPerRow = 3;
alert(numberOfLinksPerRow);
// local variables
var pre = "<tr><td><div class='ms-promlink-body' id='promlink_row_";
var post = "'></div></td></tr>";
var numberOfLinksInCurrentRow = numberOfLinksPerRow;
var currentRow = 1
// find the number of promoted links we're displaying
var numberOfPromotedLinks = $('.ms-promlink-body > .ms-tileview-tile-root').length;
// if we have more links then we want in a row, let's continue
if (numberOfPromotedLinks > numberOfLinksPerRow) {
// we don't need the header anymore, no cycling through links
$('.ms-promlink-root > .ms-promlink-header').empty();
// let's iterate through all the links after the maximum displayed link
for (i = numberOfLinksPerRow + 1; i <= numberOfPromotedLinks; i++) {
// if we're reached the maximum number of links to show per row, add a new row
// this happens the first time, with the values set initially
if (numberOfLinksInCurrentRow == numberOfLinksPerRow) {
// i just want the 2nd row to
currentRow++;
// create a new row of links
$('.ms-promlink-root > table > tbody:last').append(pre + currentRow + post);
// reset the number of links for the current row
numberOfLinksInCurrentRow = 0 }
// move the Nth (numberOfLinksPerRow + 1) div to the current table row
$('#promlink_row_' + currentRow).append($('.ms-promlink-body > .ms-tileview-tile-root:eq(' + (numberOfLinksPerRow) + ')'));
// increment the number of links in the current row
numberOfLinksInCurrentRow++; }
}
});
</script>
I want to keep a reference only on my page passing in the parameter 3 for now.
Follow the steps below to achieve it.
1.Save the code below as js file "WrapPromotedLinks.js".
$(document).ready(function () {
// Update this value to the number of links you want to show per row
var numberOfLinksPerRow = 3;
//alert(numberOfLinksPerRow);
// local variables
var pre = "<tr><td><div class='ms-promlink-body' id='promlink_row_";
var post = "'></div></td></tr>";
var numberOfLinksInCurrentRow = numberOfLinksPerRow;
var currentRow = 1
// find the number of promoted links we're displaying
var numberOfPromotedLinks = $('.ms-promlink-body > .ms-tileview-tile-root').length;
// if we have more links then we want in a row, let's continue
if (numberOfPromotedLinks > numberOfLinksPerRow) {
// we don't need the header anymore, no cycling through links
$('.ms-promlink-root > .ms-promlink-header').empty();
// let's iterate through all the links after the maximum displayed link
for (i = numberOfLinksPerRow + 1; i <= numberOfPromotedLinks; i++) {
// if we're reached the maximum number of links to show per row, add a new row
// this happens the first time, with the values set initially
if (numberOfLinksInCurrentRow == numberOfLinksPerRow) {
// i just want the 2nd row to
currentRow++;
// create a new row of links
$('.ms-promlink-root > table > tbody:last').append(pre + currentRow + post);
// reset the number of links for the current row
numberOfLinksInCurrentRow = 0;
}
// move the Nth (numberOfLinksPerRow + 1) div to the current table row
$('#promlink_row_' + currentRow).append($('.ms-promlink-body > .ms-tileview-tile-root:eq(' + (numberOfLinksPerRow) + ')'));
// increment the number of links in the current row
numberOfLinksInCurrentRow++;
}
}
});
2.Upload the file into the folder "js-enterprise" in Site Assets library.
3.Use the references below in script editor web part in the SharePoint page to make it works.
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
<script type="text/javascript" src="../SiteAssets/js-enterprise/WrapPromotedLinks.js"></script>

Add Button into HTML Table with JavaScript without generator file

I apologize in advance, English is not my native language.
I am working on a project that was delegated to me. I am working on a webpage, that is being generated by an XSLT file. I only have access to the source code of the generated page.
What does it do: The page shows a synopsis in form of a table. The left most column (lets call that one A) and the top most row (lets call it B) are the Header (?) segments (like in this table i found on google)
There are also Buttons in the top most row to sort the table.
Now the problem: There is a button to invert the table which activates the following code. This is where the problem is
I have this java code
// FAULTY FUNCTION BEGINNING
function swap_table_horizontally_vertically() {
//This is the code I already have
// Deletes all sort buttons
for (i = 0; i <= 1000; i++) {
try {
var sort_buttons = document.getElementById('sort_buttons');
}
catch(err) {
alert(err.message);
continue;
} finally {
sort_buttons.parentNode.removeChild(sort_buttons);
}
}
//End of the Code I made
//This code was already in the file
var old_table = document.getElementById('synopsis_table'),
old_table_rows = old_table.getElementsByTagName('tr'),
cols = old_table_rows.length, rows = old_table_rows[0].getElementsByTagName('td').length,
cell, next, temp_row, i = 0, new_table = document.createElement('table');
while(i < rows) {
cell = 0;
temp_row = document.createElement('tr');
if (i == 0) {
while(cell < cols) {
next = old_table_rows[cell++].getElementsByTagName('td')[0];
temp_row.appendChild(next);
}
new_table.appendChild(temp_row);
++i;
}
else {
while(cell < cols) {
next = old_table_rows[cell++].getElementsByTagName('td')[0];
temp_row.appendChild(next);
}
new_table.appendChild(temp_row);
++i;
}
}
old_table.parentNode.replaceChild(new_table, old_table);
new_table.setAttribute("id", "synopsis_table");
}
// FAULTY FUNCTION END
Now what I need is a way to add the buttons again into the new table head (top most row) with a class and id attribute.
To summarize: I need to delete the buttons from the previous top most row (because the left column shouldn't have them) and add them again to the new top most row (the previous left column).

OnClicks links to wrong button

I'm trying to link the button across every row to delete that row when clicked. However, every delete button is linked to the onclick delete of the last created row.
For example:
TABLE
Record 1 | deleteButton1
Record 2 | deleteButton2
Record 3 | deleteButton3
Actions:
clicks deleteButton1 ---> deletes the row with "Record 3"
clicks deleteButton1 ---> tries to delete the row with "Record 3" (a.k.a. nothing happens b/c row not found)
clicks deleteButton2 ---> tries to delete the row with "Record 3" (a.k.a. nothing happens b/c row not found)
HTML:
<table id="Table"></table>
JavaScript:
//Code snippet
for (var x = 0; x < itemArray.length; x++)
{
selectedItem = itemArray[x];
table = document.getElementById("Table");
row = table.insertRow(table.rows.length);
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell1.innerHTML = selectedItem;
cell2.innerHTML = "<button>—</button>"; //Delete button across every row.
cell2.onclick = function () { removeRow(selectedItem); };
}
function removeRow(content, where)
{
var table;
table = document.getElementById("Table");
var iter;
for (var i = 0; i < table.rows.length; i++)
{
iter = table.rows[i].cells[0].innerHTML;
if (iter == content)
{
table.deleteRow(i);
}
}
}
Each onclick function references the variable selectedItem. After your for loop, that variable is set to the last item in the array. So, every button will reference that last item. Here is a demonstration.
I suggest using Javascript's parentNode and rowIndex to allow a button to reference its own parent row.
In my example below, rowIndex returns the index number of the tr that is the parentNode for the clicked cell (td). This index number can be used to remove a table row directly.
cell2.onclick = function () { removeRow(this.parentNode.rowIndex); };
function removeRow(x) {
document.getElementById("Table").deleteRow(x);
}
Working Example (jsFiddle)
You may need something like this :
http://www.codingforums.com/javascript-programming/170869-dynamically-add-delete-reorder-rows-table.html
Here :
for (var i= startingIndex; i< tbl.tBodies[0].rows.length; i++) {
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.one.data = count; // text
// CONFIG: next line is affected by myRowObject settings
tbl.tBodies[0].rows[i].myRow.two.name = INPUT_NAME_FS; // input text
tbl.tBodies[0].rows[i].myRow.two.id = INPUT_NAME_FS + count;
tbl.tBodies[0].rows[i].myRow.three.name = INPUT_NAME_FS_DESIGN; // input text
tbl.tBodies[0].rows[i].myRow.three.id = INPUT_NAME_FS_DESIGN + count;
// CONFIG: next line is affected by myRowObj settings
// CONFIG: requires class named classy0 and classy1
tbl.tBodies[0].rows[i].className = 'classy' + (count % 2);
count++;
}

Categories

Resources