EDIT: I got it working! It turned out that I had written innerHtml instead of innerHTML. I This topic can be closed.
I am trying to use JS to put the link most recently clicked by a userinto a table row where a row is created each time a link is clicked. The list of links shown is also generated using JS.
The problem I am having is that when I click a link, the table is created with an empty row.
Here is the JS.
function processLinks()
{
var linksList = document.links; // get the document's links
var contents = "";
for ( var i = 0; i < linksList.length; ++i )
{
var currentLink = linksList[ i ];
contents += "<p style =\"background-color:red\"><a href='" + currentLink.href + "'
target='_blank' id='link" + i + "'>" +
currentLink.innerHTML + "</a></p>";
}
// if user click link var currentLink = linksList[ index of link user clicked ];
//create table
//document.getElementById("link + index to specify element 0,1,2,3, etc for
//id").onclick
document.getElementById( "links" ).innerHTML = contents;
} // end function processLinks
function insertLink(e)
{
var linksList = document.links; // get the document's links
var contents = "";
for (var i = 0; i < linksList.length; ++i)
{
if(document.getElementById("link" + i) )
{
var currentLink = linksList[i];
contents += "<p><a href='" + currentLink.href + "' target='_blank'
id='link" + i + "'>" +
currentLink.innerHTML + "</a></p>";
tbody = document.getElementById("tableBody");
var row = document.createElement("tr");
var cell = document.createElement("td");
cell.innerHtml = contents;
row.appendChild(cell);
tbody.appendChild(row);
}
}
document.getElementById("tableBody").onclick = function(){insertLink()};
}
document.addEventListener("click", insertLink, false);
window.addEventListener( "load", processLinks, false );
Related
I have a function to append table rows whenever a user selects values from checkbox popup window. If the user selects same or different check box values , the old values should be deleted. My code is not deleting/replacing the old row and somehow it deletes the name of the old row and creates extra table data values.
https://imgur.com/JjQjTaW
In this case, the second circled table row should have replaced the first circled row.
function AppendSampleTable(specimenNumberTextBoxId, specimenArray, _combinatedIdForSampleTbl) {
// var specimenNumberTextBoxId = "MOLECULAR DIAGNOSTICSSpec1";
var sampleTable = document.getElementById('ctl00_ContentPlaceHolder1_tblSample');
// var sampleTable = document.getElementById('ctl00_ContentPlaceHolder1_sampleNum6');
var specimenType = document.getElementById(specimenNumberTextBoxId).getAttribute("specimentype");
var poolSpecimenCode = document.getElementById(specimenNumberTextBoxId).getAttribute("poolspecimen");
var specimenNumber = "test";
var tableRows = $(sampleTable).find('tr');
var rowIndex = tableRows.length;
var i = 0;
var newRow;
var specimenArrayLength = specimenArray.length - 1; // Because specimenArray contains empty string for first element.
// Erase tr that has same name as requested.
var $oldRow = $(sampleTable).find('tr[name="' + _combinatedIdForSampleTbl + '"]'); //WHY IS THIS NOT WORKING OR IS IT? SHOUDL IT REMOVE OLD ROWS?// 3/28/2019
alert("old row=" + $oldRow);
$oldRow.remove();
// Append tr that contains desired values.
for (i; i < specimenArrayLength; i++) {
// If none of specimen has choosen for a pool, array will contain 'undefined', so we need to ignore that not to be appended into table.
if (specimenArray[i + 1] != undefined) {
specimenNumber = specimenArray[i + 1];
newRow = "<tr name='" + _combinatedIdForSampleTbl + "'><td class='col-xs-2'><span id='ctl00_ContentPlaceHolder1_sampleName" + (rowIndex + i + 1) + "' specimenCode='" + poolSpecimenCode + "'>POOL - " + specimenType + "</span></td><td class='col-xs-2'><span id='ctl00_ContentPlaceHolder1_sampleNum" + (rowIndex + i + 1) + "'>" + specimenNumber + "</span></td></tr>";
$(sampleTable).append(newRow);
}
}
}
I expect my code to replace the old row and not have extra empty table data values.
I rebuild a table (tbody) from the local storage. When it is necessary, I rebuild the <a> tag to get a link to an image. Contrary to what happen normally, when returning from the linked document or image to the calling document containing the rebuilt table, the cursor position nor the scrollbar position is retained, and the table is re-positioned at the beginning (row 0, col 0). I would like that the user would not have to scroll again to find it starting position (with the link) in the table.
The problem is simple to explain and I already did it. By clicking to expand a small view of a table in order to get a full view of it on a new page, I have to dynamically rebuild this table from information in the localstorage: firstly call the function storeLocOeuvresTbl() in the origin page; secondly, the function getInventOeuvresTblFromStoreLoc() in the destination page. This can be done by clicking on the link according to the code here : Le contenu de cette table peut être trié en cliquant sur les entêtes de colonnes.
Veuillez suivre ce lien
Expand
pour agrandir la table sur une page séparée..
If I follow a link from a cell in the built table in the destination page and return to this page from any other document/page accessed through this link, the cursor and scrollbar positions are lost. I suppose having to specify some property/attribute.
Which property/attribute do I have to specify for a dynamically built table so that the table from which I followed the link, does not move to the initial pos (0,0) when I return from this link. If I have to specify a property to keep the position, at which level? Div, table contained in the div, tbody?
Whit a dynamically built table, the normal behavior is perturbed.
Here is a link to a test page simplifying this problem:
http://www.danielpisters.be/testTable.html
Click bellow the table and you get a full view of the table in
http://www.danielpisters.be/testExpandTestTable.html
Move right to the column header "tLink" (all the others are "Foo", "Bar"). Then move down in the column until you reach a cell with a link. Click on it and you will see an image on another page. Returning from it, the position on the cell containing the link is lost, becoming 0,0.
// Build the table from the origin document
<script type="text/javascript">
function storeLocOeuvresTbl()
{
var oTable = document.getElementById('myOeuvresTable');
var s = "";
var stopAlert = true;
if (oTable == null) // TJC: Invalid ID, ignore it
{
alert("myOeuvresTable not found!");
return "";
}
var versIE = isIE();
var aTBODY = oTable.getElementsByTagName("tbody");
localStorage.setItem("myOeuvresTableTBlen", aTBODY.length);
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODY.length; i++)
{
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var aTR = aTBODY[i].getElementsByTagName("tr");
localStorage.setItem("myOeuvresTableTB" + i + "len", aTR.length);
for (var j = 0; j < aTR.length; j++)
{
var aTD = aTR[j].getElementsByTagName("td");
localStorage.setItem("myOeuvresTableTB" + i + "TR" + j + "len", aTD.length);
var aTDlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "TR" + j + "len"));
for (var k = 0; k < aTD.length; k++)
{
s = s + aTD[k].id + ": " + aTD[k].innerHTML + "|";
var tdId = "myOeuvresTableTB" + i + "TR" + j + "TD" + k;
var innerHTML = "";
if (aTD[k].innerHTML.length > 0)
{
innerHTML = aTD[k].innerHTML;
}
else
{
innerHTML = " ";
}
localStorage.setItem(tdId, innerHTML);
innerHTML = localStorage.getItem(tdId);
if (stopAlert == false && (versIE != false) && (versIE < 9))
{
alert("innerHTML get: " + innerHTML);
if (window.confirm("Stop Alert?"))
{
stopAlert = true;
}
}
}
s = s + "\n";
}
}
return s;
}
// Rebuild onLoad of the destination document
<script type="text/javascript">
function getInventOeuvresTblFromStoreLoc()
{
var tbl = document.getElementById('myOeuvresTable');
var s = "";
var tdId = "";
var innerHTML = "";
var aTBODYlen = 0;
var aTRlen = 0;
var aTDlen = 0;
var stopAlert = true;
var arrEvent = new Array("onMouseOver", "onMouseOut", "onClick", "onDbleClick", "onMouseUp", "onMouseDown", "onFocus", "onBlur");
var DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
if (tbl == null) // TJC: Invalid ID, ignore it
{
alert("myOeuvresTable not found!");
return "";
}
var versIE = isIE();
aTBODYlen = parseInt(localStorage.getItem("myOeuvresTableTBlen"));
// set the CSS class for each one of the TR tags
for (var i = 0; i < aTBODYlen; i++)
{
// get an array of all the TR tags in the TBODY
// TJC: It's actually a NodeList, but you can largely
// treat it as an array
var tblBody = tbl.tBodies.item(i);
aTRlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "len"));
for (var j = 0; j < aTRlen; j++)
{
var row = document.createElement("tr");
aTDlen = parseInt(localStorage.getItem("myOeuvresTableTB" + i + "TR" + j + "len"));
for (var k = 0; k < aTDlen; k++)
{
var cell = document.createElement("td");
tdId = "myOeuvresTableTB" + i + "TR" + j + "TD" + k;
innerHTML = localStorage.getItem(tdId);
if (innerHTML.substr(0, 7).toLowerCase() == "<a href")
{
var link = document.createElement("a");
var indDblQuote1 = innerHTML.indexOf('"');
var indDblQuote2 = innerHTML.indexOf('"', indDblQuote1 + 1);
var indOf1 = innerHTML.indexOf(">");
var indOf2 = innerHTML.toLowerCase().indexOf("</a>");
var cellLink = innerHTML.substring(indDblQuote1 + 1, indDblQuote2);
var cellText = innerHTML.substring(indOf1 + 1, indOf2);
if (stopAlert == false && (versIE != false) && (versIE < 9))
{
var s = "innetHTML: " + innerHTML + "; " + "cellLink: " + cellLink + "; " + "cellText: " + cellText;
alert(s);
if (window.confirm("Stop Alert?"))
{
stopAlert = true;
}
}
link.setAttribute('href', cellLink);
link.appendChild(document.createTextNode(cellText));
cell.appendChild(link);
}
else
{
var cellText = document.createTextNode(innerHTML);
cell.appendChild(cellText);
}
row.appendChild(cell);
s = s + tdId + ": " + innerHTML + "|";
}
tblBody.appendChild(row);
s = s + "\n";
}
tbl.appendChild(tblBody);
}
return s;
}
</script>
I'm currently using the jQuery get method to read a table in another page which has a list with files to download and links to others similar webpages.
$.get(filename_page2, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find(target_element_type_page2 + '#' + target_element_id_page2)[0];
var container = document.getElementById(element_change_content_page1);
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var isFolder = table.getAttribute("CType") == "Folder";
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link = elem.getElementsByTagName("A")[0].getAttribute("href");
if (!isFolder) {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + link + "\">" + text + "</a></li>";
} else {
container.innerHTML += "<li class=\"folderlist\">" + "<a class=\"folderlink\" onclick=\"open_submenu(this)\" href=\"#\">" + text + "</a><ul></ul></li>";
var elem_page1 = container.getElementsByTagName("li");
var container_page1 = elem_page1[elem_page1.length - 1].getElementsByTagName("ul")[0];
create_subfolder(container_page1, link);
}
}
} else {
container.innerHTML += "<li class=\"mainfolderfile\">" + "<a class=\"filelink\" href=\"" + "#" + "\">" + "Error..." + "</a></li>";
}
}, page2_datatype);
This is working fine, and all the folders and files are being listed. But when I try to do the same thing with the folders (calling the create_subfolder function) and create sublists with their subfolders and files, I'm getting a weird behavior.
function create_subfolder(container2, link1) {
$.get(link1, function(response, status){
var data = $("<div>" + response + "</div>");
var target_element = data.find("table" + "#" + "onetidDoclibViewTbl0")[0];
if (typeof target_element !== "undefined"){
var rows = target_element.rows;
for (var i = 1, n = rows.length; i < n; i++) {
var table = rows[i].cells[1].getElementsByTagName("TABLE")[0];
var elem = table.rows[0].cells[0];
var text = elem.innerText || elem.textContent;
var link2 = elem.getElementsByTagName("A")[0].getAttribute("href");
//nothing is changed in the webpage. The modifications in the html don't appear
container2.innerHTML += "<li>" + text + "</li>";
}
}
alert(container2.innerHTML); // Print the html with all the modifications
}, "html");
}
The second get(), inside the create_subfolder() function are not changing anything in the webpage, so no sublist is created. But, when I call the alert() function at the end of the get() function, it prints the code with all the modifications it should have made in the html at the second get callback. I believe the problem is related with the asynchronous behavior of the get function but I don't know exactly why. Any guess?
I need some help. I am trying to iterate through some Json items, create some li's with some information from the items, but also attach click handlers for the li's, but with a value transmited as parameter.
The problem is that the last value of that parameter is set for or the li's in the list. From what i searched i understood that it has something to do with javascript closure, but can't seem to understand how to fix it.
I am using jQuery and here is the code:
for (var i = 0; i < items.length; i++)
{
// information that will be displayed for each video
var entry = items[i];
var title = entry.title;
var image = entry.thumbnail.hqDefault;
var id = entry.id;
var li = $("<li class='video-single'>");
li.append("<img src='" + image + "' alt='" + title + "'>");
li.append("<h4>" + title + "</h4>");
$(li).click(function() {
displayPopUp(id);
});
ul.append(li);
}
Could anyone please help me fix this code?
Best regards, Marius.
The issue is that JS is function scoped so the id within your closure is the last id from your for loop. To fix this use forEach so you run each iteration of your loop in a separate scope e.g.
items.forEach(function (el, i) {
// information that will be displayed for each video
var entry = items[i];
var title = entry.title;
var image = entry.thumbnail.hqDefault;
var id = entry.id;
var li = $("<li class='video-single'>");
li.append("<img src='" + image + "' alt='" + title + "'>");
li.append("<h4>" + title + "</h4>");
$(li).click(function() {
displayPopUp(id);
});
ul.append(li);
});
you need delegated event as elements are created dynamically, you can use class that is being added on li which is video-single:
$(document).on('click','.video-single',function() {
displayPopUp(id);
});
you can read about Delegated Events HERE
in order to bind an event to a dynamically added element you need to delegate it as below:
for (var i = 0; i < items.length; i++)
{
// information that will be displayed for each video
var entry = items[i];
var title = entry.title;
var image = entry.thumbnail.hqDefault;
var id = entry.id;
var li = $("<li class='video-single'>");
li.append("<img src='" + image + "' alt='" + title + "'>");
li.append("<h4>" + title + "</h4>");
$(document).bind('click',li,function() {
displayPopUp(id);
});
ul.append(li);
}
This is my problem: I have a ul list that has undertemined number of li, because it depends the number of the files in a folder. It lists those files in a div, and when the mouse hovers one of them, I want it till get the new link only in its div.
My code is this:
function showImages(data) {
var ul = "<ul id='productImages'>";
for (i = 0; i < data.length; i++) {
var tempButton = i;
var link = '#Html.ActionLink("Pedir Detalhes","ContactUs", new { tempVerifyButton = 3}, new { #class = "visualize"})';
var directories = data[i];
ul += "<li id = 'element" + i.toString() + "'><img src='../Content/images/Products/" + directories.ImageName + "' /><div class = 'description'><div id = 'productsText'>" + directories.DescriptionName + "</div></div></li>";
}
ul += "</ul>";
$("#directoryImages").append(ul);
for (i = 0; i < data.length; i++) {
var element = "ul#productImages li#element" + i.toString();
$(element).hover(
function () {
var link = '#Html.ActionLink("Pedir Detalhes","ContactUs", new { tempVerifyButton = 3 }, new { #class = "visualize"})';
$(".description").append("<div class = 'visualize'>" + link + "</div>");
});
}
}
The problem with this code is when the mouse hovers one of the li element, all .description gets the link, and I want only the current hovered li till get the link, and then when it loses focus the link disappears.
EDITED:
I already use $(this).append($(".description").append("< div class = 'visualize'>" + link + "< /div>"));
Any ideas?
Try with this(current element)
$(this).append("<div class = 'visualize'>" + link + "</div>");
http://learn.jquery.com/javascript-101/this-keyword/
this is a special keyword that is used in methods to refer to the object on which a method is being invoked.