Return String variable delayed - javascript

I have a web page with a table identified by "table-rank" class.
This table has 3 pages : to go on next page, i use the .click function on the net button.
I tried to build a finalHtml string by capturing specific element in each lines of the table.
Problem : The finalHtml contains 3 times the datas of the first page of the table. No data of the second page and third page is captured..
It's because, when i click on the button, it's asynchronous, and the first loop continue to parse the table which have not been already refreshed. How can i do, to be sure that the data have been loaded when i click on the next button ?
function getClassement() {
var finalHtml = '' ;
for (var k=0; k<2; k++) {
for (var i=0; i<$(".table-rank tbody tr").length; i++) {
var currentLine = $(".table-rank tbody tr")[i];
// Get position
var positionEl = $(currentLine).find(".ng-binding")[0];
var position = $(positionEl).text();
// Get id
var idEl = $(currentLine).find(".ng-binding")[1];
var id = $(idEl).text();
// Get prenom/nom
var nomPrenom = "test";
// Nombre de paris
var nbrParisEl = $(currentLine).find(".ng-binding")[2];
var nbParis = $(nbrParisEl).text();
// Nombre de bons paris
var nbrBonsParisEl = $(currentLine).find(".ng-binding")[3];
var nbBonsParis = $(nbrBonsParisEl).text();
// Score exacts
var scoresExactsEl = $(currentLine).find(".ng-binding")[4];
var scoresExacts = $(scoresExactsEl).text();
// Points totals
var pointsTotalEl = $(currentLine).find(".ng-binding")[7];
var pointsTotals = $(pointsTotalEl).text();
finalHtml = finalHtml + "<tr><td><span class='position'>"+position+"</span></td><td>"+id+"</td><td>"+nomPrenom+"</td><td>"+nbParis+"</td><td>"+nbBonsParis+"</td><td>"+scoresExacts+"</td><td><span class='total'>"+pointsTotals+"</span></td></tr>";
}
// Go next page
$(".pager a")[1].click();
}
return finalHtml;
}

Related

Google Slides API / Apps Script - find URLs and make them into hyperlinks

My script pulls rows from a form-populated spreadsheet and applies the values to a slide template.
They submit a Title, Description, and a Link to the resource they are submitting.
I need the "Link", which should be submitted as an URL, to automatically become a hyperlink when the slide is created. Everything I've tried has returned an error. I want to run .setLinkUrl(link) on the previously inserted link text. I just cant get it to stick. Any help would be appreciated.
--below is the function I'm trying to run--
function dataInjectionNN() {
var dataSpreadsheetUrl = "...spreadsheeturl.urlytypestuff..."
var ss = SpreadsheetApp.openByUrl(dataSpreadsheetUrl);
var deck = SlidesApp.getActivePresentation();
var mathCluster = deck.getName();
// Logger.log(mathCluster)
var sheet = ss.getSheetByName(mathCluster);
var lastR = sheet.getLastRow();
var range =sheet.getDataRange();
// Logger.log(range.getLastRow() + " Is the last Column.");
var values = range.getValues();
// Logger.log(values);
var slides = deck.getSlides();
var presLength = slides.length;
var templateSlide = slides[1];
values.forEach(function(page){
// run if the presentation has less slides that the number of form entries
if((presLength-2) < lastR){
if(page[3] = mathCluster){
var title = page[9];
var link = page[10];
var desc = page[11];
templateSlide.duplicate();//Duplicate the template page
slides = deck.getSlides();//update the slides array for indexes and length
newSlide = slides[2]; //declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('<<Title>>',title);
shape.getText().replaceAllText('<<Link>>',link);
shape.getText().replaceAllText('<<Description>>',desc);
presLength = slides.length;
newSlide.move(presLength);
})
}
}
});
}

call method with param in an other method

I'm trying to learn Vue.js and I have a problem.
How can I add the handler "addRowHandlers" in the function addUpHandler ?
I made a pagination system and when I turn the page 1, I lost my handler on the .
It's a basic system. I'm not making a new database request, I use a twig variable which contain all my datas
addUpHandler: function(){
//let up = document.getElementById('up');
//let pageA = 1
const text = document.getElementById('textSearchByName')
if(text.value != ""){
this.pageT += 1
return searchByName(pageT)
}
let myTab = document.getElementById("myTab")
myTab.innerHTML = ""
this.pageA++;
for(let i=(this.pageA-1)*10;i<this.pageA*10;i++){
let dist = segments[i]['distance']/1000
myTab.innerHTML += "<tr v-on:click='addRowHandlers($event)'><td>"+segments[i]['name']+"</td><td>"+segments[i]['nbSegment']+"</td><td>"+dist.toFixed(2)+"km</td><td>"+segments[i]['total_elevation_gain']+"m</td><td>"+segments[i]['average_grade']+"%</td><tr>"
}
},
addRowHandlers: function(event){
this.clearMap();
var td = event.currentTarget.getElementsByTagName("td").length
var cell = event.currentTarget.getElementsByTagName("td")[0]; //get le premier td de la ligne
var polyline = cell.firstElementChild.value;
var idSeg = cell.firstElementChild.nextElementSibling.value
let distance = event.currentTarget.getElementsByTagName("td")[2]
distance = distance.firstElementChild.value
this.getStreams(idSeg, distance, myChart)
var coordonnee = L.Polyline.fromEncoded(polyline).getLatLngs();
L.polyline(
coordonnee,
{
color: 'red',
weight: 2
}
).addTo(map)
},
regards
PS: SOrry for my english

JavaScript : Delete dynamically created table

I am new to web development and struggling with deleting a dynamically created table.
Below is the JavaScript function to create the table when user clicks a button.
function DrawTable(data){
var oTHead = myTable.createTHead();
var oTFoot = myTable.createTFoot();
var oCaption = myTable.createCaption();
var oRow, oCell;
var i, j;
var heading = new Array();
heading[0] = "AAA";
heading[1] = "BBB";
heading[2] = "CCC";
heading[3] = "DDD";
var tableData = data.split(':');
// Insert a row into the header.
oRow = oTHead.insertRow(-1);
oTHead.setAttribute("bgColor","lightskyblue");
// Insert cells into the header row.
for (i=0; i < heading.length; i++)
{
oCell = oRow.insertCell(-1);
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.innerHTML = heading[i];
}
// Insert rows and cells into bodies.
for (i=0; i < tableData.length; i++)
{
var oBody = oTBody0;
oRow = oBody.insertRow(-1);
var splitData = tableData[i].split(',');
for (j=0; j < splitData.length; j++)
{
oCell = oRow.insertCell(-1);
oCell.innerHTML = splitData[j];
}
}
}
The above code works perfectly and draws the table when user clicks on the button.
If user clicks on the button again it will draw the table again.
i.e., it will draw another header and all the rows all over again.
At this point I want to delete the existing header and rows and draw it all new.
I tried many things to delete the existing table, but nothing works.
Is there a way I can make sure that the table is not duplicated again?
UPDATE
The HTML part is:
<table id="myTable">
<tbody ID="oTBody0"></tbody>
</table>
ANOTHER UPDATE
I tried below and it worked.
oTHead.innerHTML = "";
oTBody0.innerHTML = "";
jQuery offers a .empty() function that you can use
$("#myTable").empty();
Or with javascript you can just set the innerHTML to empty
document.getElementById("myTable").innerHTML = "";
Just execute this function before you start trying to add new content to the table.
//$("#myTable").empty();
document.getElementById("myTable").innerHTML = "";
// Insert a row into the header.
oRow = oTHead.insertRow(-1);
oTHead.setAttribute("bgColor","lightskyblue");
// Insert cells into the header row.
for (i=0; i < heading.length; i++) {
oCell = oRow.insertCell(-1);
oCell.align = "center";
oCell.style.fontWeight = "bold";
oCell.innerHTML = heading[i];
}
Since you're using jQuery, just do this: $('#containerIdThatYourTableSitsIn').html('');
That will clear the html of whatever element your table sits in. Then just reload it.
Edit
As the comments have mentioned, .empty() is another option.

Something not right with AJAX code

I have a page with a menu of categories and subcategories of products.
Categories have a class 'category' and subcategories have a class 'subcategory'. When either is clicked some AJAX sends the category to some php to compile the html which the AJAX then sends back to the page to populate a div. This part works fine.
There is a function in the code to split the returned records. So say there are 6 records and the page is to show 2 at a time then there are 3 pages. I get the correct amount of pages displayed(1 2 3) but all 6 records displayed on each!
Can anyone see the problem?
$('a.category, a.subcategory').click(function (e) {
// first stop the link to go anywhere
e.preventDefault();
// get the class of the link
var linkClass = $(this).attr("class");
//get the text of the link by converting the clicked object to string
var linkText = new String(this);
// the value after the last / is the category ID
var categoryValue = linkText.substring(linkText.lastIndexOf('/') + 1);
// put the post parameters into 'params' to pass through the AJAX post request
var params = {};
params[linkClass] = categoryValue;
// send the category ID to the getProductData.php script using jquery ajax post method
// send along a category ID
// on success insert the returned text into the chosen div
$.post('../inc/showproducts.php', params, function (data) {
//find total number of records
var totalRecords = $(data).length;
//define how many records shown per page
var pageSize = 2
//work out number of pages needed to hold records
var numOfPages = Math.ceil(totalRecords / pageSize);
//make page links
var i,
pageLinks = '<div class="pageLinks">';
for (i = 0; i < numOfPages; i++) {
pageLinks += '<a href="#" onclick="showProductPage(' + i + ');return false;">' + (i + 1) + '<\/a> ';
}
pageLinks += '<\/div>';
//display returned data and page links in chosen div (.showproduct)
$('.showproduct').html(pageLinks + data);
showProductPage(0);
});
});
//function to slice up records into pages
function showProductPage(pageNo) {
var perPage = 2;
var start = pageNo * perPage;
var end = start + perPage;
$('.image').hide().filter(function (index) {
return ((index > (start - 1)) && (index < end));
}).show();
}
//check out this line of your code
$('.showproduct').html(pageLinks + data);
The data var has all the records in it still. You have to get each data[position] with a for loop that iterates based on pageSize * pageNum. So page 1 would look like
var iterationSize = pageSize * pageNum; //(2 * 1 = 2)
var i;
var j = 0;
var pageData[];
for(i = pageNum - 1; i < iterationSize; i++, j++){
pageData[j] = data[i];
}
$('.showproduct').html(pageLinks + pageData.join(''));

Storing the index of a for loop in javascript

I'm developing an android app with phonegap. I'm making an HTML table with some that with a for loop from localStorage. I need, for each row, to store the index i of the for to use it for retrieving an item from localStorage that has the name like the index. I have some code but the variable that i defined for that effect gets overwritten by the loop (of course). Here's the code:
<script language="javascript">
if(len != 0) {
var table = document.getElementById('hor-minimalist-b'); // get the table element
var tableBody = table.childNodes[1]; // get the table body
var tableHead = table.childNodes[0]; // get the table head
var thead = document.createElement('th');
var row2 = document.createElement('tr'); // create a new row
var headText = document.createTextNode('Dados');
thead.scope = "col";
thead.appendChild(headText);
row2.appendChild(thead);
tableHead.appendChild(row2);
for (var i=0; i<len; i++) {
var row = document.createElement('tr'); // create a new row
var cell = document.createElement('td'); // create a new cell
var a = document.createElement('a');
var cellText = document.createTextNode(localStorage.getItem('key' + i));
var xyz = "key" + i;
a.href = "alterar.html";
a.onclick = function() { doLocalStorage(xyz) };
a.appendChild(cellText);
cell.appendChild(a); // append input to the new cell
row.appendChild(cell); // append the new cell to the new row
tableBody.appendChild(row); // append the row to table body
}}
</script>
</table>
Maybe i'm not explaining myself too well. If you need any more info please ask. Thanks in advance. Eva
try to put the key name in to a closure:
function wrapper(i) {
return function() {
doLocalStorage("key" + i)
}}
a.onclick = wrapper(i);
Not sure if I got your question right, but if you want to bind usage of a variable asynchronously when doing for loop then you should wrap it in a closure:
for(i = 1, c = arr.length; i < c; i++){
(function(i){
// i wont change inside this closure so bound events will retain i
$('#id'+i).click(function(){
alert(i); // Will alert the corresponding i
})
})(i);
}

Categories

Resources