I'm attempting to creating a hyperlink within a cell of a table, but currently the hyperlink just displays as text within the table. Looking at the console I can see linkElement is getting created properly as:
text
My JS code
//Creating the table
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
//creating URL elements
linkElement = document.createElement("a");
linkElement.setAttribute("href", url);
var linkText = document.createTextNode(url);
linkElement.append(linkText);
console.log(linkElement)
cell1.innerHTML = linkElement;
cell2.innerHTML = appVersion;
My HTML:
<table id="myTable">
</table>
Use cell1.append(linkElement), cell1.innerHTML is meant to be use when providing the HTML as string not an object.
Figured it out using cell1.innerHTML= ''+linkElement+'';
Related
I'm making an API call whose result is displayed in a table. Say, the columns are 'isbn', 'name of book', 'published year'. Every row would have a copy to clipboard icon that would copy the isbn value into clipboard.
To be specific, I'm unable to copy the data["isbn"] into the clipboard, when the user clicks the copy button.
What I tried to do was to obtain the data["isbn"] and store it as foo's (input id = 'foo') value. As clipboard functions work with elements like input, etc.
Code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/2.0.8/clipboard.min.js"></script>
<script>
async function books_data{
const response = await fetch('/books');
const data = await response.json();
var table = document.getElementById("myTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
document.getElementById("foo").value = val["JobID"];
cell1.innerHTML = data["isbn"];
cell2.innerHTML = data["name"];
cell3.innerHTML = data["year"];
cell4.innerHTML = '<button class="btn" data-clipboard-target="#foo"> Copy to clipboard </button>" ';
}
</script>
<div>
<input id="foo" style="display: none">
...
...
</div>
I'm unclear where I'm going wrong. I referred these:
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand, https://clipboardjs.com/
The most popular method for Copy to Clipboard is involving Document.execCommand, which seems to be deprecated.
This question already has answers here:
How to make changes to HTML document permanent using Javascript?
(3 answers)
Closed 3 years ago.
I've got a really basic HTML page that simply displays a table. I'm trying the below code so that I can add a new row to the bottom of the table each time the page is loaded (even if it's the same data for now). However, each time I load the page, the bottom element keeps getting overridden with the same data. I am trying to do something like this example on W3 Schools (without the button, but the same concept).
My code is as follows:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<table id="table" style="width:70%; text-align: center;">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Row</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
<script>
function myFunction() {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
};
myFunction();
</script>
</body>
</html>
I've also tried replacing myFunction above with document.addEventListener("DOMContentLoaded", function(){...}, but that hasn't solved my issue either.
JavaScript will not make permanent changes in your HTML files.
This means that after you load the page, your HTML code will be displayed and then the function will be executed, adding a new row.
After you reload again, the same process will happen, and the row will be added after the end of your second HTML row.
It doesn't matter whether you use the simple method on your code or the other one you suggest (with document.addEventListener), this function is bound to be executed only once and will not add more than one row.
The issue is that your page isn't storing its data anywhere, so whenever you reload the page you're basically destroying any data you've modified and loading it from scratch again. You should use localStorage or a local database or something like that to keep track of data, and save your page's state when the function is called or on page unload.
In pseudocode:
const loadFromLocalStorage = () => {
const rows = localStorage.getItem("extra_rows") // extra_rows can be an array
for(elem in rows) {
// add to table
}
}
const saveToLocalStorage = (obj) => {
const rows = localStorage.getItem("extra_rows")
localStorage.setItem([...rows, obj])
}
const addNewRow = () => {
var table = document.getElementById("table");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
cell3.innerHTML = "NEW CELL3";
const obj = {
cell1: cell1, cell2: cell2, cell3: cell3
}
saveToLocalStorage(obj)
}
const myFunction = () => {
loadFromLocalStorage()
addNewRow()
}
myFunction()
I'm not so good at Javascript and can't get one thing working.
I have a table, something like this:
<table>
<tr><td>test #1</td><td>Here we go1!</td></tr>
<tr><td>test #2</td><td>Here we go2!</td></tr>
<tr><td>test #3</td><td>Here we go3!</td></tr>
</table>
And I need to insert new row with some content (not clone) after row with pressed link.
So in other words, after pressing on <a> in first row, the table have to be like this:
<table>
<tr><td>test #1</td><td>Here we go1!</td></tr>
<tr><td>some content here</td><td>some content here</td></tr>
<tr><td>test #2</td><td>Here we go2!</td></tr>
<tr><td>test #3</td><td>Here we go3!</td></tr>
</table>
I really tried to do something but it was always inserting before of after table.
UPDATE:
My JS code to insert new row looks something like this:
(I tried to use one solution posted here but it doesn't work).
function RowAdd()
{
var table=document.getElementById("test");
var last=$(this).closest("tr").prevAll().length;
var row=table.insertRow(last);
row.insertCell(0);
row.cells[0].innerHTML="test";
row.insertCell(1);
row.cells[1].innerHTML="test";
row.insertCell(2);
row.cells[2].innerHTML="test";
}
If I understand you need to do that, right ?
http://jsfiddle.net/OxyDesign/v7swo505/
JS (with jQuery)
$(document).ready(function(){
$('body').on('click','table a', function(e){
$(this).closest('tr').after('<tr><td>New Content 1</td><td>New Content 2</td></tr>');
});
});
Assuming your table has an id=myTable, you can use:
var table = document.getElementById("myTable");
var row = table.insertRow(1); //inserts row at index 1, like in your example
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "data1";
cell2.innerHTML = "data2";
This will work with other examples or deleting them too.
<body>
<table id="myTable">
<tr><td>test #1</td><td>Here we go1!</td></tr>
<tr><td>test #2</td><td>Here we go2!</td></tr>
<tr><td>test #3</td><td>Here we go3!</td></tr>
<tr><td>test #4</td><td>Here we go4!</td></tr>
<tr><td>test #5</td><td>Here we go5!</td></tr>
</table>
</body>
<script>
var table = document.getElementById("myTable");
var row = table.insertRow(1); //inserts row at index 1, like in your example
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "data1";
cell2.innerHTML = "data2";
// This line becomes the 4th line after the insert.
// But it has the row value of 3, because row 1 is 0
// <tr><td>test #3</td><td>Here we go3!</td></tr>
var row = table.deleteRow(3); //inserts row at index 1, like in the example
</script>
https://jsfiddle.net/vr_driver/zjaoqbyh/7/
I have a table with 1 row, 11 columns. Now I generated the following JavaScript code to add a new row using a Button.
The issue is, when i refresh the page, the new rows that i added using this javascript, are lost. I want them to be saved permanently in the HTML file. How can this be done?
<script>
function AddNewRow()
{
var table = document.getElementById("table1");
var row = table.insertRow(1);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
var cell8 = row.insertCell(8);
var cell9 = row.insertCell(9);
var cell10 = row.insertCell(10);
</script>
The HTML file remains on a server inaccessible to the client, but it would be perfectly possible for the browser to save the added information - either in HTML form, or as a more storage-focused format like XML/JSON. It would then need to be loaded back into Javascript and re-added to the page each time your page starts up.
Read up on the localStorage documentation at Mozilla - they could give you a general idea of storing/loading. With the innerHTML readable/writable property, hopefully you have an idea of how you could accomplish this.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#localStorage
I'm trying to create a button to put in the each row of a table to remove that row
the table row it self will be created by javascript on the runtime
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell2 = row.insertCell(0);
cell2.innerHTML='deleterow';
var cell2 = row.insertCell(1);
cell2.innerHTML='price';
var cell3 = row.insertCell(2);
cell3.innerHTML='name';
}
here is my removing row function
function removerow(i){
var table = document.getElementById('baskettbl');
table.deleteRow(i);
}
my problem is when i remove a row if that row is in the middle of my table it will mess up the indexing cuz i define removerow argument when i creat each row
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell2 = row.insertCell(0);
cell2.innerHTML='<a href="" onclick="removerow('+rowCount+'); return false; />
like if i have 5 rows and and i remove row[3] i will end up with 4 rows but my last row button is still going to pass 5 to the removerow function and of course there is no row[5]
so i thought i should re index all of the rows by simply
function removerow(i){
var table = document.getElementById('baskettbl');
table.deleteRow(i);
}
var rowCount = table.rows.length;
for(i=0 , i<= rowCount ; i++){
var cell = 'cell'+i;
cell.innerHTML='<a href="" onclick="removerow('+0+'); return false; />
}
but i need to set the td id in the numeric whey so i can change their innerhtml like this
so here is my questions :
1.how can i set the attribute like id to the created td so i can get their values later? here is how i create them
var cell2 = row.insertCell(0);
2.i findout about rowIndex property which apparently returns the row index
function removerow(x)
{
alert("Row index is: " + x.rowIndex);
}
so that is going to make my job easy and i don't need to recreate all the indexes but how can i pass the clicked row 'this' to the the function ? here is how i pass the index
var cell2 = row.insertCell(0);
cell2.innerHTML='<a href="" onclick="removerow('+rowCount+'); />
and also i use dreamweaver cs5 and it doesn't seems to recognize rowIndex
Then get the index dynamically and don't set it when you create it:
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl'),
rowCount = table.rows.length,
row = table.insertRow(rowCount),
cell = row.insertCell(0),
a = document.createElement('a');
a.href = '#';
a.innerHTML = 'deleterow';
a.onclick = function() {
// `this` refers to the `a` element.
removerow(this.parentNode.parentNode.rowIndex);
return false;
};
cell.appendChild(a);
cell = row.insertCell(1);
cell.innerHTML='price';
cell = row.insertCell(2);
cell.innerHTML='name';
// still needed for IE memory leak? Don't know...
table = row = cell = a = null;
};
Setting the click event handler via JavaScript is more readable anyway (well, you could also just use this.parentNode.... in the HTML string).
The code above should do what you want (if you have questions about it, just comment). Nevertheless I wanted to answer your questions:
how can i set the attribute like id to the created td so i can get their values later?
An important thing to know is that there is a difference between HTML attributes and DOM properties. These answers describe it quite well, although it is originally about jQuery (but that does not matter).
Anyway, you already know how to set the innerHTML and you can do so similar for id:
cell.id = "something";
Have a look at the DOM element reference.
but how can i pass the clicked row 'this' to the the function
I more or less showed this in the code above. Inside the event handler, this refers to the element you bound the event to. We know that it is an a element which is a child of a td element, which itself is a child of a tr element. So to get the corresponding row, we can access this.parentNode.parentNode.
For further information regarding JavaScript, have a look at the javascript tag information page. There you will find a lot of useful links to introductions about various JavaScript related topics.
Especially have a look at the articles about event handling at quirksmode.org.
Try this I hope this helps you.
function createrow(){
document.getElementById('totaltd').innerHTML = total;
var table = document.getElementById('baskettbl');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = "row_"+rowCount;
var cell2 = row.insertCell(0);
cell2.innerHTML='deleterow';
var cell2 = row.insertCell(1);
cell2.innerHTML='price';
var cell3 = row.insertCell(2);
cell3.innerHTML='name';
}
function removerow(i){
var table = document.getElementById('baskettbl');
table.removeChild(document.getElementById("row_"+i));
}